最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to create a date object from a date-string which contains AMPM? - Stack Overflow

programmeradmin1浏览0评论

Is there any way to define a javascript date object with AM/PM value?

Something like this

var startDate = new Date("1900-1-1 8:20:00 PM");

Is there any way to define a javascript date object with AM/PM value?

Something like this

var startDate = new Date("1900-1-1 8:20:00 PM");
Share Improve this question edited Dec 24, 2011 at 12:40 Šime Vidas 186k65 gold badges286 silver badges391 bronze badges asked Dec 24, 2011 at 12:21 Pawan NogariyaPawan Nogariya 8,97013 gold badges59 silver badges128 bronze badges 8
  • @pablochan I get "invalid date"... – Šime Vidas Commented Dec 24, 2011 at 12:28
  • @pablochan Nope, it doesn't return me proper value when I try to call startDate.getHours(), it returns NaN, while when I define date like this var startTime = new Date(1900,1,1,8,20,0); call to getHours() properly returns 8 :( – Pawan Nogariya Commented Dec 24, 2011 at 12:34
  • @Bakudan-ханювиги—no, it will not. Date.parse is very browser dependent. To reliably convert a string to a date object, it must be parsed manually. – RobG Commented Dec 24, 2011 at 12:37
  • @PawanNogariya A 8PM time should return 20, not 8. – Šime Vidas Commented Dec 24, 2011 at 12:37
  • @PawanNogariya: It works in Chrome but apparently not everywhere. Check my answer. – pablochan Commented Dec 24, 2011 at 12:37
 |  Show 3 more comments

4 Answers 4

Reset to default 12

This works:

new Date( '1 Jan 1900 8:20:00 PM' )

and is equivalent to

new Date( '1 Jan 1900 20:20:00' )

Live demo: http://jsfiddle.net/cVE2E/

you can use Date.parse

var startDate = new Date(Date.parse("1900-1-1 8:20:00 PM"));

This depends on the browser and/or the locale. But I found a script that can help: http://blog.stevenlevithan.com/archives/date-time-format

There is no guarantee that the Date.parse() method, and hence the new Date() constructor can parse any specific date format. By the ECMAScript standard, only a specific ISO 8601 format and some implementation-dependent formats need to be processed.

Thus, for portability at least, you need to use other tools, such as the Globalize.js library; using it, you would use

Globalize.parseDate('1900-1-1 8:20:00 PM','yyyy-M-d h:mm:ss tt')

which returns a Date object when the first argument matches the format specified by the second argument.

If you need to process alternative date formats on input, you may need to write code that tries reading the data using specific formats until it gets a non-null result.

发布评论

评论列表(0)

  1. 暂无评论