简体   繁体   English

在 javascript 中获取没有时间的日期 ISO 字符串

[英]Get date ISO string without time in javascript

Is there a way to obtain a ISO string of a new date type in javascript with time at midnight without rebuilding a new date with date parts nor formatting it?有没有办法在 javascript 中获取新日期类型的 ISO 字符串,时间为午夜,而无需重建带有日期部分的新日期或对其进行格式化?

I've been trying this我一直在尝试 这个

var date = new Date();
date.setHours(0, 0, 0, 0);
document.write(date.toISOString());

and I am getting this我得到这个

2017-04-20T04:00:00.000Z

I want to get this我想得到这个

2017-04-20T00:00:00.000Z

Is there a built-in function or way as I 've been trying to do to get the desired output (with rebuilding a date object with the date parts)?是否有内置的 function 或我一直试图获得所需的 output 的方法(用日期部分重建日期 object)?

 var isoDate = new Date().toISOString().substring(0,10); console.log(isoDate);

Just use setUTCHours instead of setHours and compensate for timezone:只需使用setUTCHours而不是setHours并补偿时区:

 var date = new Date(); var timezoneOffset = date.getMinutes() + date.getTimezoneOffset(); var timestamp = date.getTime() + timezoneOffset * 1000; var correctDate = new Date(timestamp); correctDate.setUTCHours(0, 0, 0, 0); document.write(correctDate.toISOString())

setHours will set time in your local timezone, but when you display it, it will show the time in UTC. setHours将在您的本地时区设置时间,但是当您显示它时,它将以 UTC 显示时间。 If you just set it as UTC from the beginning, you'll get the result you want.如果您从一开始就将其设置为 UTC,您将得到您想要的结果。

EDIT :编辑

Just be aware that if you are ahead of UTC, your date will be stored as a UTC date from the previous day, so running setUTCHours will not work as intended, changing your date to midnight of the previous day.请注意,如果您于 UTC,您的日期将存储为前一天的 UTC 日期,因此运行setUTCHours将无法按预期工作,将您的日期更改为前一天的午夜。 Therefore, you first need to add the timezone offset to the date.因此,您首先需要将时区偏移量添加到日期。

If you want your code to be logically persistent, a substring based on hard coded indexes is never safe:如果您希望您的代码在逻辑上是持久的,那么基于硬编码索引的子字符串永远不会安全:

var iso = date.toISOString();
iso = iso.substring(0, iso.indexOf('T'));

with date-fns format日期格式

import {format} from "date-fns-tz"    
format(new Date(), 'yyyy-MM-dd')

If you can live with depending on the great momentjs.com library, it will be as easy as this:如果你可以依赖于伟大的momentjs.com库,那就很简单了:

moment().format('YYYY-MM-DD');

or或者

moment().toISOString();

One liner, without third party lib:一个班轮,没有第三方库:

const date = new Date().toISOString().split('T')[0]; // Ex: '2023-01-17'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM