简体   繁体   English

标准JavaScript中的日期格式

[英]Date Format in standard JavaScript

I have a date in "Mar 15, 2017 5:06:16 PM" format and i have to convert it into browser's timezone which i am doing using "Date" in javascript but the final time i am getting is in "3/15/2017, 5:06:16 PM" format i have to change it to "Mar 15, 2017 5:06:16 PM" 我有“ 2017年3月15日下午5:06:16 PM”格式的日期,我必须将其转换为浏览器所在的时区,我正在使用JavaScript中的“日期”进行操作,但我得到的最后时间是“ 3/15” / 2017,5:06:16 PM“格式,我必须将其更改为” 2017年3月15日5:06:16 PM“

How this can be achieved using JavaScript? 使用JavaScript如何做到这一点?

I have tried JavaScript inbuilt functions like 我已经尝试过JavaScript内置函数,例如

(1) toISOString (1)toISOString

(2) toLocalString (2)toLocalString

(3) toUTCString (3)toUTCString

but no luck, i feel like there is no standard js method. 但没有运气,我觉得没有标准的js方法。 can anyone provide me that piece of code which can change it into the desired format ? 谁能提供给我那段可以将其更改为所需格式的代码?

You don't have to use different methods, you can simply use string manipulation, if you want a custom date string display and don't want to load any additional libraries such as momentjs: 如果您要显示自定义日期字符串,并且不想加载任何其他库(例如momentjs),则不必使用其他方法,只需使用字符串操作即可:

var months = [ 'Jan', ... ];
var parts = Date.toString() // 3/15/2017, 5:06:16 PM
            .split('/');    // [ "3", "15", "2017, 5:06:16 PM" ]

console.log( months[ parts[ 0 ] ] + " " + parts[ 1 ] + ", " + parts[ 2 ] );

This is definitely not the only solution, but whenever you want to change the display format of anything, you can always remind yourself that you can use string manipulation. 绝对不是唯一的解决方案,但是只要您想更改任何内容的显示格式,就可以随时提醒自己可以使用字符串操作。 A more semantically correct way to do it would be not to do any string manipulation, but by placing Date.getMonth in the wanted part of a string, for example. 这样做在语义上更正确的方法是不执行任何字符串操作,而是将Date.getMonth放置在字符串的所需部分中。

If you're using ES6, you can make it very pretty: 如果您使用的是ES6,则可以使其非常漂亮:

console.log( `${monthString} ${dayNum}, ${yearNum} ${hourNum % 12}:${leftPad(minuteNum,2)}:${leftPad(secondNum,2)} ${hourNum < 12 ? 'PM' : 'AM'} ` );

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

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