[英]How to convert an ISO date to the date format yyyy-mm-dd?
Just crop the string:只需裁剪字符串:
var date = new Date("2013-03-10T02:00:00Z");
date.toISOString().substring(0, 10);
Or if you need only date out of string.或者,如果您只需要字符串中的日期。
var strDate = "2013-03-10T02:00:00Z";
strDate.substring(0, 10);
Try this试试这个
date = new Date('2013-03-10T02:00:00Z');
date.getFullYear()+'-' + (date.getMonth()+1) + '-'+date.getDate();//prints expected format.
Update:-更新:-
As pointed out in comments, I am updating the answer to print leading zeros for date and month if needed.正如评论中所指出的,如果需要,我正在更新答案以打印日期和月份的前导零。
date = new Date('2013-08-03T02:00:00Z'); year = date.getFullYear(); month = date.getMonth()+1; dt = date.getDate(); if (dt < 10) { dt = '0' + dt; } if (month < 10) { month = '0' + month; } console.log(year+'-' + month + '-'+dt);
You could checkout Moment.js , Luxon , date-fns or Day.js for nice date manipulation.您可以查看 Moment.js 、 Luxon 、 date- fns或Day.js以获得不错的日期操作。
Or just extract the first part of your ISO string, it already contains what you want.或者只是提取 ISO 字符串的第一部分,它已经包含您想要的内容。 Here is an example by splitting on the T
:这是在T
上拆分的示例:
"2013-03-10T02:00:00Z".split("T")[0] // "2013-03-10"
And another example by extracting the 10 first characters:另一个例子是提取前 10 个字符:
"2013-03-10T02:00:00Z".substr(0, 10) // "2013-03-10"
This is what I do to get date only:这就是我为获取日期所做的工作:
let isoDate = "2013-03-10T02:00:00Z"; alert(isoDate.split("T")[0]);
let isoDate = "2013-03-10T02:00:00Z"; var d = new Date(isoDate); d.toLocaleDateString('en-GB'); // dd/mm/yyyy d.toLocaleDateString('en-US'); // mm/dd/yyyy
Moment.js will handle date formatting for you. Moment.js将为您处理日期格式。 Here is how to include it via a JavaScript tag, and then an example of how to use Moment.js to format a date.下面是如何通过 JavaScript 标签包含它,然后是如何使用 Moment.js 格式化日期的示例。
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>
moment("2013-03-10T02:00:00Z").format("YYYY-MM-DD") // "2013-03-10"
Moment.js is pretty big library to use for a single use case. Moment.js是一个非常大的库,用于单个用例。 I recommend using date-fns
instead.我建议改用date-fns
。 It offers basically the most functionality of Moment.js with a much smaller bundle size and many formatting options
.它基本上提供了 Moment.js 的大部分功能,但包的大小要小得多,而且formatting options
很多。
import format from 'date-fns/format'
format('2013-03-10T02:00:00Z', 'YYYY-MM-DD'); // 2013-03-10, YYYY-MM-dd for 2.x
One thing to note is that, since it's the ISO 8601 time format, the browser generally converts from UTC time to local timezone.需要注意的一件事是,由于它是ISO 8601时间格式,因此浏览器通常会从 UTC 时间转换为本地时区。 Though this is simple use case where you can probably do '2013-03-10T02:00:00Z'.substring(0, 10);
尽管这是一个简单的用例,您可能可以执行'2013-03-10T02:00:00Z'.substring(0, 10);
. .
For more complex conversions date-fns
is the way to go.对于更复杂的转换date-fns
是要走的路。
Using toLocaleDateString
with the Canadian locale returns a date in ISO format.将toLocaleDateString
与加拿大语言环境一起使用会返回 ISO 格式的日期。
function getISODate(date) {
return date.toLocaleDateString('en-ca');
}
getISODate(new Date()); // '2022-03-24'
To all who are using split, slice and other string-based attempts to obtain the date, you might set yourself up for timezone related fails!对于所有使用 split、slice 和其他基于字符串的尝试来获取日期的人来说,您可能会为与时区相关的失败设置自己!
An ISO-String has Zulu-Timezone and a date according to this timezone, which means, it might use a date a day prior or later to the actual timezone, which you have to take into account in your transformation chain. ISO-String 具有 Zulu-Timezone 和根据此时区的日期,这意味着它可能使用实际时区之前或之后一天的日期,您必须在转换链中考虑到这一点。
See this example:看这个例子:
const timeZoneRelatedDate = new Date(2020, 0, 14, 0, 0);
console.log(timeZoneRelatedDate.toLocaleDateString(
'ja-JP',
{
year: 'numeric',
month: '2-digit',
day: '2-digit'
}
).replace(/\//gi,'-'));
// RESULT: "2020-01-14"
console.log(timeZoneRelatedDate.toISOString());
// RESULT: "2020-01-13T23:00:00.000Z" (for me in UTC+1)
console.log(timeZoneRelatedDate.toISOString().slice(0,10));
// RESULT: "2020-01-13"
利用:
new Date().toISOString().substring(0, 10);
Pass your date in the date object:在日期对象中传递您的日期:
var d = new Date('2013-03-10T02:00:00Z');
d.toLocaleDateString().replace(/\//g, '-');
This will output the date in YYYY-MM-DD format:这将以 YYYY-MM-DD 格式输出日期:
let date = new Date();
date = date.toISOString().slice(0,10);
If you have a date object:如果你有一个日期对象:
let date = new Date() let result = date.toISOString().split`T`[0] console.log(result)
or或者
let date = new Date() let result = date.toISOString().slice(0, 10) console.log(result)
The best way to format is by using toLocaleDateString with options格式化的最佳方法是使用带有选项的 toLocaleDateString
const options = {year: 'numeric', month: 'numeric', day: 'numeric' };
const date = new Date('2013-03-10T02:00:00Z').toLocaleDateString('en-EN', options)
Check Date section for date options here https://www.w3schools.com/jsref/jsref_tolocalestring.asp在此处检查日期部分的日期选项https://www.w3schools.com/jsref/jsref_tolocalestring.asp
To extend on rk rk 's solution : In case you want the format to include the time, you can add the toTimeString()
to your string, and then strip the GMT part, as follows:扩展rk rk的解决方案:如果您希望格式包含时间,您可以将toTimeString()
添加到您的字符串中,然后toTimeString()
GMT 部分,如下所示:
var d = new Date('2013-03-10T02:00:00Z');
var fd = d.toLocaleDateString() + ' ' + d.toTimeString().substring(0, d.toTimeString().indexOf("GMT"));
If you have the timezone you can do:如果你有时区,你可以这样做:
const myDate = "2022-10-09T18:30:00.000Z"
const requestTimezone = "Asia/Calcutta";
const newDate = new Date(myDate).toLocaleString("en-CA", {
dateStyle: "short",
timeZone: requestTimezone,
});
console.log(newDate)
>> 2022-10-10
Another outputs:另一个输出:
const myDate = "2022-10-02T21:00:00.000Z"
const requestTimezone = "Asia/Jerusalem";
>> 2022-10-03
const myDate = "2022-09-28T04:00:00.000Z"
const requestTimezone = "America/New_York";
>> 2022-09-28
let dt = new Date('2013-03-10T02:00:00Z');
let dd = dt.getDate();
let mm = dt.getMonth() + 1;
let yyyy = dt.getFullYear();
if (dd<10) {
dd = '0' + dd;
}
if (mm<10) {
mm = '0' + mm;
}
return yyyy + '-' + mm + '-' + dd;
I used this:我用过这个:
HTMLDatetoIsoDate(htmlDate){
let year = Number(htmlDate.toString().substring(0, 4))
let month = Number(htmlDate.toString().substring(5, 7))
let day = Number(htmlDate.toString().substring(8, 10))
return new Date(year, month - 1, day)
}
isoDateToHtmlDate(isoDate){
let date = new Date(isoDate);
let dtString = ''
let monthString = ''
if (date.getDate() < 10) {
dtString = '0' + date.getDate();
} else {
dtString = String(date.getDate())
}
if (date.getMonth()+1 < 10) {
monthString = '0' + Number(date.getMonth()+1);
} else {
monthString = String(date.getMonth()+1);
}
return date.getFullYear()+'-' + monthString + '-'+dtString
}
Source: http://gooplus.fr/en/2017/07/13/angular2-typescript-isodate-to-html-date/来源: http : //gooplus.fr/en/2017/07/13/angular2-typescript-isodate-to-html-date/
var d = new Date("Wed Mar 25 2015 05:30:00 GMT+0530 (India Standard Time)"); alert(d.toLocaleDateString());
Many of these answers give potentially misleading output if one is looking for the day in the current timezone.如果要查找当前时区的日期,其中许多答案可能会产生误导 output 。
This function will output the day corresponding with the date's timezone offset:这 function 将 output 与日期的时区偏移对应的日期:
const adjustDateToLocalTimeZoneDayString = (date?: Date) => {
if (!date) {
return undefined;
}
const dateCopy = new Date(date);
dateCopy.setTime(dateCopy.getTime() - dateCopy.getTimezoneOffset()*60*1000);
return dateCopy.toISOString().split('T')[0];
};
Tests:测试:
it('return correct day even if timezone is included', () => {
// assuming the test is running in EDT timezone
// 11:34pm eastern time would be the next day in GMT
let result = adjustDateToLocalTimeZoneDayString(new Date('Wed Apr 06 2022 23:34:17 GMT-0400'));
// Note: This is probably what a person wants, the date in the current timezone
expect(result).toEqual('2022-04-06');
// 11:34pm zulu time should be the same
result = adjustDateToLocalTimeZoneDayString(new Date('Wed Apr 06 2022 23:34:17 GMT-0000'));
expect(result).toEqual('2022-04-06');
result = adjustDateToLocalTimeZoneDayString(undefined);
expect(result).toBeUndefined();
});
Misleading approach:误导性的做法:
To demonstrate the issue with the other answers' direct ISOString().split()
approach, note how the output below differs from what one might expect:为了演示其他答案的直接ISOString().split()
方法的问题,请注意下面的 output 与人们可能期望的有何不同:
it('demonstrates how the simple ISOString().split() may be misleading', () => {
// Note this is the 7th
expect(new Date('Wed Apr 06 2022 23:34:17 GMT-0400').toISOString().split('T')[0]).toEqual('2022-04-07');
});
Simpler way to get Year Or Month获取年份或月份的更简单方法
let isoDateTime = "2013-03-10T02:00:00Z";
console.log(isoDateTime.split("T")[0]); //2013-03-10
Using Split Method使用拆分方法
console.log(isoDateTime.split("-")[0]); //2013
console.log(isoDateTime.split("-")[1]); //03
WARNING: Most of these answers are wrong.警告:这些答案中的大多数都是错误的。
That is because toISOString()
always returns the UTC date, not local date.这是因为toISOString()
总是返回 UTC 日期,而不是本地日期。 So, for example, if your UTC time is 0500
and your timezone is GMT-0800
, the day returned by toISOString()
will be the UTC day, which will be one day ahead of the local timezone day.因此,例如,如果您的 UTC 时间是0500
并且您的时区是GMT-0800
,则toISOString()
返回的日期将是 UTC 日期,比本地时区日期早一天。
You need to first convert the date to the local date.您需要先将日期转换为本地日期。
const date = new Date();
date.setTime(date.getTime() - date.getTimezoneOffset()*60*1000)
Now date.toISOString()
will always return the proper date according to the local timezone.现在date.toISOString()
将始终根据当地时区返回正确的日期。
But wait, there's more.但是等等,还有更多。 If we are also using toTimeString()
that will now be wrong because time is now local and toTimeString()
assumes it is UTC and converts it.如果我们还使用toTimeString()
那现在是错误的,因为时间现在是本地时间并且toTimeString()
假定它是 UTC 并转换它。 So we need to first extract toTimeString()
as a variable before doing the conversion.所以我们需要先将toTimeString()
提取为变量,然后再进行转换。
The Date()
class in javascript is inconsistent because of this and should really be updated to avoid this confusion. javascript 中的Date()
class 因此不一致,因此应该更新以避免这种混淆。 The toISOString()
and toTimeString()
methods should both do the same default things with respect to timezone. toISOString()
和toTimeString()
方法都应该对时区执行相同的默认操作。
Use the below code.使用下面的代码。 It is useful for you.它对你有用。
let currentDate = new Date()
currentDate.toISOString()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.