admin管理员组

文章数量:1194548

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?

Share Improve this question edited Jun 13, 2023 at 5:29 Carson 7,9482 gold badges56 silver badges54 bronze badges asked Apr 4, 2019 at 6:07 ChetanChetan 711 gold badge1 silver badge6 bronze badges 1
  • 3 filename = `any_name_${new Date().toJSON().slice(0,10)}.zip` – adiga Commented Apr 4, 2019 at 6:12
Add a comment  | 

4 Answers 4

Reset to default 15

You can use template literals to accomplish this:

let filename = `any_name_${(new Date().toJSON().slice(0,10))}.zip`
console.log(`Add here ${filename}`);

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

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.

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`;

本文标签: datetimehow to provide the date as filename using javascriptStack Overflow