i have written some code in javascript, and i want to use today's date as my file name, even i tried below code but it wont work for me.
filename=${`any_name_${new Date().toJSON().slice(0,10)}.zip
can anyone help me with it?
i have written some code in javascript, and i want to use today's date as my file name, even i tried below code but it wont work for me.
filename=${`any_name_${new Date().toJSON().slice(0,10)}.zip
can anyone help me with it?
You can use template literals to accomplish this:
let filename = `any_name_${(new Date().toJSON().slice(0,10))}.zip`
console.log(`Add here ${filename}`);
All the answers listed above just create a new Date, then look at the first part of it. However, JS Dates include timezones. As of writing this (1/6/22 @ 9PM in Eastern/US), if I run:
let filename = `any_name_${(new Date().toJSON().slice(0,10))}.zip`
console.log(`Add here ${filename}`);
it falsely gives me tommorows date (1/7/22). This is because Date() just looking at the first part of the date is ignoring the timezone.
A better way to do this that takes into account timezones is:
var today = new Date();
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
var yyyy = today.getFullYear();
filename = mm + '-' + dd + '-' + yyyy + '.zip';
console.log(filename);
Adapted from here.
You can use string concatenation:
var filename="any_name_" + new Date().toJSON().slice(0,10) + ".zip";
console.log(filename)
Output:
any_name_2019-04-04.zip
If you are using ES6 standards, we can use Template_literals Ref : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
const filename = `any_name_${new Date().toJSON().slice(0,10)}.zip`;