Pawan Nogariya
Pawan Nogariya

Reputation: 8990

How to create a date object from a date-string which contains AM/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");

Upvotes: 11

Views: 7673

Answers (4)

Jukka K. Korpela
Jukka K. Korpela

Reputation: 201866

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.

Upvotes: 0

Šime Vidas
Šime Vidas

Reputation: 186083

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/

Upvotes: 12

pablochan
pablochan

Reputation: 5715

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

Upvotes: 0

Naren Sisodiya
Naren Sisodiya

Reputation: 7288

you can use Date.parse

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

Upvotes: 0

Related Questions