4

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?

Carson
  • 6,105
  • 2
  • 37
  • 45
Chetan
  • 71
  • 1
  • 1
  • 6

4 Answers4

13

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
  • 34,372
  • 9
  • 61
  • 83
ABC
  • 2,068
  • 1
  • 10
  • 21
4

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
  • 466
  • 3
  • 15
3

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,439
  • 1
  • 15
  • 26
  • 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
  • 1
    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
1

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
  • 946
  • 1
  • 15
  • 23
Aravind Anil
  • 153
  • 1
  • 9