Javascript:将具有完整月份的字符串转换为日期对象 [英] Javascript: convert string with full month to date object

查看:45
本文介绍了Javascript:将具有完整月份的字符串转换为日期对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串变量"PublishDate" ,然后当我使用"PublishDate.value" 检查该值时,它会返回一个类似

I have a string variable "PublishDate" and then when I check the value using "PublishDate.value" it returns a string like

"2016年10月4日上午9:28"

我需要将其转换为日期对象,该对象的格式应为"10/04/2016"

I need to convert it to a date object that is formatted like "10/04/2016"

我不确定这是如何在javascript中完成的:

I am not sure how this is done in javascript:

var d = new Date("October 04, 2016 9:28 AM");
var date = d.getDate();
var month = d.getMonth();
var year = d.getFullYear();
var hours = d.getHours();
var min = d.getMinutes();   //10/04/2016
console.log(month+1+'/'+date+'/'+year);

推荐答案

首先,使用


编辑:请始终考虑浏览器可能不支持您的格式的情况.对于Firefox,MDN声明它将支持


Always consider the case that your format may not be supported by the browser. In the case of Firefox, the MDN states that it will support certain date formats:

该字符串应采用Date.parse()方法可识别的格式(符合IETF的RFC 2822时间戳以及ISO8601的版本.)

The string should be in a format recognized by the Date.parse() method (IETF-compliant RFC 2822 timestamps and also a version of ISO8601).

IE的MSDN Javascript参考也说:

它首先尝试使用 ISO日期格式.如果日期字符串不是ISO格式,JavaScript会尝试解析通过使用其他其他日期格式.

It first tries to parse a date string by using the ISO Date Format. If the date string is not in ISO format, JavaScript tries to parse the date by using other Other Date Formats.

此外,请考虑MDN本身不鼓励使用构造函数或 Date.parse()解析String日期,即使它适用于您的特定情况:

Also, consider that the MDN itself discourages parsing String dates using the constructor or Date.parse(), even though it works for your specific case:

注意:使用Date构造函数解析日期字符串(以及强烈建议不要使用Date.parse,它们等效)浏览器的差异和不一致之处.

Note: parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies.

如果您需要支持其他各种日期格式或各种浏览器,也可以考虑 Momtent.js javascript库或使用RegEx自己解析,例如@RobG和@adeneo的答案.

If you need to support other varieties of date formats or a variety of browsers, you can also consider Momtent.js javascript library or do your own parsing with RegEx, like in @RobG's and @adeneo's answers.

然后,您需要提取所需的部分(月,日,年),并将它们以斜杠作为分隔符的字符串连接起来,例如@ user3254198的答案或@Steeve Pitis的答案:

Then, you need to extract the parts you want (month, day, year) and concatenate them in a string with the slash as a separator, like in @user3254198's answer or @Steeve Pitis's answer:

d.getDate() + '/' 
    + (d.getMonth() + 1) + '/' 
    +  d.getFullYear()

请记住, PublishDate.value.getMonth()方法返回该月的从零开始的月数字表示形式,因此,如果要使用1-12的值,请添加一个 +1.

Remember that the PublishDate.value.getMonth() method returns a zero-based month numerical representation of the month, so if you want a 1-12 value, add a +1 to it.

请随时提出任何进一步要求!祝你好运.

Feel free to ask any further! Good luck.

这篇关于Javascript:将具有完整月份的字符串转换为日期对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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