2

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?

Azzabi Haythem
  • 2,141
  • 7
  • 25
  • 30
Chetan
  • 35
  • 1
  • 6

4 Answers4

10

You can use template literals to accomplish this:

let filename = `any_name_${(new Date().toJSON().slice(0,10))}.zip`
console.log(`Add here ${filename}`);
adiga
  • 31,610
  • 8
  • 53
  • 74
ABC
  • 2,000
  • 1
  • 9
  • 20
2

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.

Luke Vanzweden
  • 341
  • 2
  • 12
1

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
glhr
  • 4,152
  • 1
  • 14
  • 24
  • As i use console.log=(`${(new Date().toJSON().slice(0,10).toString())}.zip`); and it's working fine. – Chetan Apr 04 '19 at 06:31
  • You can do `console.log("any_name_" + new Date().toJSON().slice(0,10) + ".zip")` – glhr Apr 04 '19 at 06:32
  • I just want to print the date as file name, without affecting any other character. console.log("any_name_" + new Date().toJSON().slice(0,10) + ".zip") – if i use this approach then the file name will get print ""any_name_2019-04-04.zip"" like this. – Chetan Apr 04 '19 at 06:37
  • If you only want the date followed by `.zip`, do `console.log(new Date().toJSON().slice(0,10) + ".zip")` – glhr Apr 04 '19 at 06:38
  • Please consider marking an answer as accepted (check mark on the left) since your issue was solved. – glhr Apr 04 '19 at 06:42
0

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`;
Typhon
  • 706
  • 1
  • 11
  • 19
Aravind Anil
  • 143
  • 1
  • 9