0

How would I format a date in javascript in the format: June 2, 2013, 1:05 p.m.

Here is a relevant link, but I'm still having trouble getting this exact formatting, based on Date(). http://www.webdevelopersnotes.com/tips/html/10_ways_to_format_time_and_date_using_javascript.php3

David542
  • 104,438
  • 178
  • 489
  • 842

4 Answers4

1

This should be useful to you: http://blog.stevenlevithan.com/archives/date-time-format

Alex Polkhovsky
  • 3,340
  • 5
  • 29
  • 37
1

i would suggest moment.js. here it is: http://momentjs.com/

import it and do this

moment().format('LLL'); 

this is what you want

doniyor
  • 36,596
  • 57
  • 175
  • 260
1

Why not write a function to get bits of the date for you and return an Object which lets you build a string as easily as string concatenation of Object properties.

The example below will always base answer on UTC time

var easyDate = (function () {
    var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
        months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
        thstndrd = ['th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th'];
    return function (d) {
        var dow = d.getUTCDay(),
            dom = d.getUTCDate(),
            moy = d.getUTCMonth(),
            y = d.getUTCFullYear(),
            h = d.getUTCHours(),
            m = d.getUTCMinutes(),
            s = d.getUTCSeconds();
        return {
            dom: '' + dom,
            th: thstndrd[dom % 10],
            day: days[dow],
            moy: '' + (moy + 1),
            month: months[moy],
            year: '' + y,
            ampm: h < 12 ? 'a.m.' : 'p.m.',
            hh: h < 10 ? '0' + h : '' + h,
            sh: '' + (h % 12 || 12),
            mm: m < 10 ? '0' + m : '' + m,
            ss: s < 10 ? '0' + s : '' + s,
        };
    };
}());

var o = easyDate(new Date());
// Object {dom: "2", th: "nd", day: "Sunday", moy: "6", month: "June"…}
o.month + ' ' + o.dom + ', ' + o.sh + ':' + o.mm + ' ' + o.ampm;
// "June 2, 8:43 p.m."
Paul S.
  • 64,864
  • 9
  • 122
  • 138
0

At w3schools you can find a complete reference to Javascript's Date object

Then you can use the methods to combine into a string of your liking.

var d = new Date();

d.getHours() + ":" + ...

There isn't a method to get the month name, you will need to get the number and create a switch.

The hour is in 24h format, so you have to convert and calculate if it is am or pm.

The day and year you can get directly using getDate() and getFullYear()

References

BrunoLM
  • 97,872
  • 84
  • 296
  • 452
  • If you're linking to documentation, link to the MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date – Blender Jun 02 '13 at 20:14