This question already has an answer here:
- Formatting the date time with Javascript 11 answers
I need to change a date/time from 2014-08-20 15:30:00 to look like 08/20/2014 3:30 pm
Can this be done using javascript's Date object?
This question already has an answer here:
I need to change a date/time from 2014-08-20 15:30:00 to look like 08/20/2014 3:30 pm
Can this be done using javascript's Date object?
I don't think that can be done RELIABLY with built in methods on the native Date object. The
toLocaleString
method gets close, but if I am remembering correctly, it won't work correctly in IE < 10. If you are able to use a library for this task, MomentJS is a really amazing library; and it makes working with dates and times easy. Otherwise, I think you will have to write a basic function to give you the format that you are after.You can do that:
Fiddle
Please do not reinvent the wheel. There are many open-source & COTS solutions that already exist to solve this problem.
Please take a look at the following JavaScript libraries:
Moment.js: [Source] | [Minified]
Datejs: [Source] | [Alpha1.zip (1.6MB)]
Demo
I wrote a one-liner using Moment.js below. You can check out the demo here: JSFiddle.
Yes, you can use the native javascript Date() object and its methods.
For instance you can create a function like:
And display also the am / pm and the correct time.
Remember to use getFullYear() method and not getYear() because it has been deprecated.
DEMO http://jsfiddle.net/a_incarnati/kqo10jLb/4/
For the date part:(month is 0-indexed while days are 1-indexed)
for the time you'll want to create a function to test different situations and convert.
hope this helps