简体   繁体   English

将JavaScript日期转换为格式化的字符串

[英]Convert JavaScript Date to formatted String

I have a JavaScript Date object and want to convert it into String like this: 2018-05-24T11:00:00+02:00 我有一个JavaScript Date对象,并希望将其转换为这样的字符串: 2018-05-24T11:00:00 + 02:00

var dateObj = new Date("Thu May 24 2018 11:00:00 GMT+0200");

function convertToString(dateObj) {
    // converting ...
    return "2018-05-24T11:00:00+02:00";
}

You can use moment.js , it handles pretty much all the needs about date formatting you may have. 您可以使用moment.js ,它可以处理几乎所有有关日期格式的需求。

var dateObj = new Date("Thu May 24 2018 11:00:00 GMT+0200");
console.log(moment(dateObj).format())

You have quite the options to represent the DateTime object as a string. 您有很多选项可以将DateTime对象表示为字符串。 This question was already elaborated on in the following StackOverflow answers: 以下StackOverflow答案中已经详细说明了这个问题:

Personally, I would sacrifice a few extra lines in my document for the Vanilla JavaScript variant. 就个人而言,我会在文档中为Vanilla JavaScript变体牺牲一些额外的行。 This way I would have complete control of the format and of the function responsible for the formatting - easier debugging and future changes. 这样,我就可以完全控制格式和负责格式化的功能-更容易调试和将来的更改。 In your case that would be (using string literals to shorten the code): 在您的情况下(使用字符串文字来缩短代码):

var date = new Date("Thu May 24 2018 11:00:00 GMT+0200");

function convertToString(date) {
  return `${date.getFullYear()}-${date.getMonth()}-${date.getDate()}-...`;
}

And so on. 等等。 On this page Date - JavaScript | 此页面上的日期-JavaScript | MDN , in the left you have all the methods that extract some kind of information from the Date object. MDN ,在左侧,您具有从Date对象提取某种信息的所有方法。 Use them as you wish and you can achieve any format you desire. 根据需要使用它们,可以实现所需的任何格式。 Good luck! 祝好运!

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

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