简体   繁体   English

如何在JavaScript中以正确的格式格式化日期

[英]How to format date in correct format in JavaScript

I'm working on JavaScript and stuck in a small issue. 我正在研究JavaScript并陷入一个小问题。

I am receiving this date in JSON response 1322919399447-0500 我在JSON回复1322919399447-0500收到此日期

and I want to format this like: 6:50 PM, Dec 3rd 2011 . 我希望格式化为: 6:50 PM, Dec 3rd 2011

I used this handy little date format addon and it worked very well for me. 我使用了这个方便的小日期格式插件 ,它对我来说非常好用。 Even took care of the pesky internet explorer quirks with the month. 这个月甚至照顾了讨厌的互联网浏览器怪癖。

I'm not sure if this is the best way (I'm sure it's not, actually), but essentially you can make that datestring into a js Date object, then pull out the pieces to manipulate as you see fit: 我不确定这是不是最好的方式(我确定它不是,实际上),但实质上你可以将日期字符串变成一个js Date对象,然后根据你的需要拉出碎片进行操作:

var dateThing = new Date(1322919399447-0500);
dateThing.getFullYear(); // 2011
dateThing.getDay(); // 6
dateThing.getDate(); // 3
dateThing.getMonth(); // 11
dateThing.getHours(); // 8 (test for anything over 12, that indicates PM)
dateThing.getMinutes(); // 36

Then you can concatenate those pieces into your own format. 然后,您可以将这些部分连接成您自己的格式。 Like I said, there's probably a better way, but this works in a pinch. 就像我说的那样,可能有更好的方法,但这种方法很有效。

Here is the snippet with your example input. 以下是您的示例输入的代码段。 It is using script linked by Zoidberg . 它是使用脚本Zoidberg链接。

This code returns formatted UTC date. 此代码返回格式化的UTC日期。 If you want your local date then remove UTC: from the return statement. 如果您想要本地日期,请从return语句中删除UTC: .

function convertTime(dateString) {
  // get ms part from the string
  var milis = +dateString.substring(0, 13);
  // get timezone part as "# of hours from UTC", e.g. "-0500" -> -5
  var offset = +dateString.substring(13, 16);
  // move the time for "offset" number of hours (to UTC time)
  var date = new Date(milis - offset * 3600000);
  // using http://stevenlevithan.com/assets/misc/date.format.js
  return date.format("UTC:h:MM TT, mmm dS yyyy");
}

EDIT : Changed + offset * to - offset * as we want to normalize to UTC. 编辑 :将+ offset *更改为- offset *因为我们要将其标准化为UTC。

This is a similar date format function I created that uses the same flags that PHP's date function uses. 这是我创建的类似日期格式函数,它使用与PHP日期函数相同的标志。

PHP date function in Javascript Javascript中的PHP日期函数

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

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