繁体   English   中英

如何将 ISO 日期和时间格式转换为“DD Mon YYYY hh:mm:ss”?

[英]How to convert ISO date and time format to “DD Mon YYYY hh:mm:ss”?

我有一个这样的变量,

var date = "2016-04-07T03:03:03Z";

如何使用 JavaScript/jQuery 将其转换为本地时区6 Apr 2016, 8:03:03 PM这样的时间格式?

使用Date.prototype.toLocaleDateString()函数的解决方案:

var date_str = "2016-04-07T03:03:03Z",
    options = { year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit'},
    formatted = (new Date(date_str)).toLocaleDateString('en-US', options),
    date_parts = formatted.substring(0, formatted.indexOf(",")).split(" ").reverse().join(" ");

var formatted_date = date_parts + formatted.substr(formatted.indexOf(",") + 1);

console.log(formatted_date);

输出将如下所示(根据您的语言环境):

7 Apr 2016, 6:03:03 AM

试试这个:

var date = "2016-04-07T03:03:03Z";
var myDate = new Date(date);

console.log(myDate);

2016 年 4 月 7 日星期四 05:03:03 GMT+0200(西欧夏令时)

new Date(date)转换为本地时区

如果您想对值进行更多控制,还可以设置日期格式,请参阅此文章了解更多信息

编辑 2021-02-26 :考虑使用更现代的库,例如https://date-fns.org/

原文:

由于您想用时区解析它然后格式化输出,我强烈建议使用Moment.js ,它是一个很好用的时间和日期操作库:

代码看起来像这样:

var date = "2016-04-07T03:03:03Z";
console.log(moment(date).format('D MMM YYYY, h:mm:ss A')); 
// "7 Apr 2016, 5:03:03 AM"

我试过一些可能对你有帮助的东西。

编辑:更新了我的代码片段以将军事时间格式化为标准时间

 function formatDate ( today ) { var newDateItems = new Array(); var dateItems = String(today).split(" "); dateItems.forEach(function(item, index){ if (index > 0 && index < 5) { if (index == 4){ item = getStandardTime(item); } newDateItems.push(item); } }); return newDateItems.join(" "); } //To format military time into standard time function getStandardTime( time ) { time = time.split(":"); var hh = Number(time[0]); var mm = Number(time[1]); var ss = Number(time[2]); var timeValue = ""; if (hh > 12) timeValue += hh - 12; else timeValue += hh; if (mm < 10) timeValue += ":0" + mm; else timeValue += ":" + mm if (ss < 10) timeValue += ":0" + ss; else timeValue += ":" + ss timeValue += (hh >= 12) ? " PM" : " AM"; return timeValue } var dateToday = new Date(); document.write(formatDate(dateToday));

这是一个也使用type-script的函数,如果是一位数,还会在分钟和小时前加上0

function convertISODateToTimeFormat(ISODate: string) {
      const newDateObj = new Date(ISODate);
      const toMonth = newDateObj.getMonth() + 1;
      const toYear = newDateObj.getFullYear();
      const toDate = newDateObj.getDate();
      const toHours = newDateObj.getHours();
      const toHoursProcessed = (toHours < 10 ? '0' : '') + toHours;
      const toMin = newDateObj.getMinutes();
      const toMinProcessed = (toMin < 10 ? '0' : '') + toMin;
      const dateTemplate = `${toDate}.${toMonth}.${toYear} ${toHoursProcessed}:${toMinProcessed}`;
      // console.log(dateTemplate)
      return dateTemplate;
    }
    convertISODateToTimeFormat('2019-08-07T02:01:49.499Z')

暂无
暂无

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

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