格式日期使用javascript [英] format date using javascript

查看:84
本文介绍了格式日期使用javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JavaScript中格式化日期有问题,这是我的函数代码

have problem for format date in JavaScript, this is my function code

   //originalDate = '2016-03-02 09:12:14.989522';
   var d = new Date(originalDate),
        month = d.getMonth() + 1,
        day =d.getDate(),
        year = d.getFullYear(),
        hour = d.getHours(),
        min = d.getMinutes();
    alert([day, month, year].join('-')+' '+[hour,min].join(':'));

我的原始日期='2016-03-02 09:12: 14.989522';
和我的代码总是返回'南南南南:南',看到未知的originalDate我通过至。
任何帮助?

and my original date ='2016-03-02 09:12:14.989522'; and my code always return 'Nan-Nan-Nan Nan:Nan', It's seen unknown originalDate that I pass to. any help?

注意:我的日期数据库中的数据类型为 timestamp

Note: datatype in database of date of mine is timestamp

推荐答案

简单解决方案:将日期字符串中的空格替换为T。

Simple solution: Replace the space in your date string with a "T".

(但是,要完全在技术上是正确的,您还应该在最后添加一个时区指示符,或者添加一个Z来表示UTC,即协调世界时,或+ hh:mm或-hh:mm表示时区偏移。)

(However, to be completely technically correct, you should also include a time zone indicator at the end, either an additional "Z" to indicate UTC, i.e. Coordinated Universal Time, or "+hh:mm" or "-hh:mm" to indicate a time zone offset.)

写道:

The MDN site for Date.parse() writes:


由于解析日期字符串的方差,...结果不一致,特别是在不同的ECMAScript实现中诸如2015-10-12 12:00:00的字符串可能会被解析为NaN,UTC或当地时区。

Because of the variances in parsing of date strings, ...results are inconsistent, especially across different ECMAScript implementations where strings like "2015-10-12 12:00:00" may be parsed to as NaN, UTC or local timezone.


日期时间字符串可能是ISO 8601格式。

The date time string may be in ISO 8601 format.

上文提及的ISP 8601规格


格式如下。这里显示的组件确实必须存在,正好是这个标点符号。请注意,T字面上出现在字符串中,表示ISO 8601中规定的时间元素的开头。

The formats are as follows. Exactly the components shown here must be present, with exactly this punctuation. Note that the "T" appears literally in the string, to indicate the beginning of the time element, as specified in ISO 8601.


完成日期加上小时,分钟,秒和
秒的小数分数YYYY-MM-DDThh:mm: ss.sTZD(例如1997-07-16T19:20:30.45 + 01:00)

Complete date plus hours, minutes, seconds and a decimal fraction of a second YYYY-MM-DDThh:mm:ss.sTZD (eg 1997-07-16T19:20:30.45+01:00)

这是代码重写的代码日期中的空格为T。如果您的浏览器无效,请在日期的末尾添加Z或时区偏移。

Here is your code re-written replacing the space in date with a "T". If that doesn't work in your browser, add a "Z" or time zone offset at the end of date.

var date ='2016-03-02T09:12:14.989522';
var d = new Date(date),
  month = d.getMonth() + 1,
  day = d.getDate(),
  year = d.getFullYear(),
  hour = d.getHours(),
  min = d.getMinutes();
document.write([day, month, year].join('-') + ' ' + [hour, min].join(':'));

这篇关于格式日期使用javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆