Current time formatting with Javascript

444,889

Solution 1

A JavaScript Date has several methods allowing you to extract its parts:

getFullYear() - Returns the 4-digit year
getMonth() - Returns a zero-based integer (0-11) representing the month of the year.
getDate() - Returns the day of the month (1-31).
getDay() - Returns the day of the week (0-6). 0 is Sunday, 6 is Saturday.
getHours() - Returns the hour of the day (0-23).
getMinutes() - Returns the minute (0-59).
getSeconds() - Returns the second (0-59).
getMilliseconds() - Returns the milliseconds (0-999).
getTimezoneOffset() - Returns the number of minutes between the machine local time and UTC.

There are no built-in methods allowing you to get localized strings like "Friday", "February", or "PM". You have to code that yourself. To get the string you want, you at least need to store string representations of days and months:

var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];

Then, put it together using the methods above:

var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
var d = new Date();
var day = days[d.getDay()];
var hr = d.getHours();
var min = d.getMinutes();
if (min < 10) {
    min = "0" + min;
}
var ampm = "am";
if( hr > 12 ) {
    hr -= 12;
    ampm = "pm";
}
var date = d.getDate();
var month = months[d.getMonth()];
var year = d.getFullYear();
var x = document.getElementById("time");
x.innerHTML = day + " " + hr + ":" + min + ampm + " " + date + " " + month + " " + year;
<span id="time"></span>

I have a date format function I like to include in my standard library. It takes a format string parameter that defines the desired output. The format strings are loosely based on .Net custom Date and Time format strings. For the format you specified the following format string would work: "dddd h:mmtt d MMM yyyy".

var d = new Date();
var x = document.getElementById("time");
x.innerHTML = formatDate(d, "dddd h:mmtt d MMM yyyy");

Demo: jsfiddle.net/BNkkB/1

Here is my full date formatting function:

function formatDate(date, format, utc) {
    var MMMM = ["\x00", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
    var MMM = ["\x01", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
    var dddd = ["\x02", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
    var ddd = ["\x03", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];

    function ii(i, len) {
        var s = i + "";
        len = len || 2;
        while (s.length < len) s = "0" + s;
        return s;
    }

    var y = utc ? date.getUTCFullYear() : date.getFullYear();
    format = format.replace(/(^|[^\\])yyyy+/g, "$1" + y);
    format = format.replace(/(^|[^\\])yy/g, "$1" + y.toString().substr(2, 2));
    format = format.replace(/(^|[^\\])y/g, "$1" + y);

    var M = (utc ? date.getUTCMonth() : date.getMonth()) + 1;
    format = format.replace(/(^|[^\\])MMMM+/g, "$1" + MMMM[0]);
    format = format.replace(/(^|[^\\])MMM/g, "$1" + MMM[0]);
    format = format.replace(/(^|[^\\])MM/g, "$1" + ii(M));
    format = format.replace(/(^|[^\\])M/g, "$1" + M);

    var d = utc ? date.getUTCDate() : date.getDate();
    format = format.replace(/(^|[^\\])dddd+/g, "$1" + dddd[0]);
    format = format.replace(/(^|[^\\])ddd/g, "$1" + ddd[0]);
    format = format.replace(/(^|[^\\])dd/g, "$1" + ii(d));
    format = format.replace(/(^|[^\\])d/g, "$1" + d);

    var H = utc ? date.getUTCHours() : date.getHours();
    format = format.replace(/(^|[^\\])HH+/g, "$1" + ii(H));
    format = format.replace(/(^|[^\\])H/g, "$1" + H);

    var h = H > 12 ? H - 12 : H == 0 ? 12 : H;
    format = format.replace(/(^|[^\\])hh+/g, "$1" + ii(h));
    format = format.replace(/(^|[^\\])h/g, "$1" + h);

    var m = utc ? date.getUTCMinutes() : date.getMinutes();
    format = format.replace(/(^|[^\\])mm+/g, "$1" + ii(m));
    format = format.replace(/(^|[^\\])m/g, "$1" + m);

    var s = utc ? date.getUTCSeconds() : date.getSeconds();
    format = format.replace(/(^|[^\\])ss+/g, "$1" + ii(s));
    format = format.replace(/(^|[^\\])s/g, "$1" + s);

    var f = utc ? date.getUTCMilliseconds() : date.getMilliseconds();
    format = format.replace(/(^|[^\\])fff+/g, "$1" + ii(f, 3));
    f = Math.round(f / 10);
    format = format.replace(/(^|[^\\])ff/g, "$1" + ii(f));
    f = Math.round(f / 10);
    format = format.replace(/(^|[^\\])f/g, "$1" + f);

    var T = H < 12 ? "AM" : "PM";
    format = format.replace(/(^|[^\\])TT+/g, "$1" + T);
    format = format.replace(/(^|[^\\])T/g, "$1" + T.charAt(0));

    var t = T.toLowerCase();
    format = format.replace(/(^|[^\\])tt+/g, "$1" + t);
    format = format.replace(/(^|[^\\])t/g, "$1" + t.charAt(0));

    var tz = -date.getTimezoneOffset();
    var K = utc || !tz ? "Z" : tz > 0 ? "+" : "-";
    if (!utc) {
        tz = Math.abs(tz);
        var tzHrs = Math.floor(tz / 60);
        var tzMin = tz % 60;
        K += ii(tzHrs) + ":" + ii(tzMin);
    }
    format = format.replace(/(^|[^\\])K/g, "$1" + K);

    var day = (utc ? date.getUTCDay() : date.getDay()) + 1;
    format = format.replace(new RegExp(dddd[0], "g"), dddd[day]);
    format = format.replace(new RegExp(ddd[0], "g"), ddd[day]);

    format = format.replace(new RegExp(MMMM[0], "g"), MMMM[M]);
    format = format.replace(new RegExp(MMM[0], "g"), MMM[M]);

    format = format.replace(/\\(.)/g, "$1");

    return format;
};

Solution 2

You may want to try

var d = new Date();
d.toLocaleString();       // -> "2/1/2013 7:37:08 AM"
d.toLocaleDateString();   // -> "2/1/2013"
d.toLocaleTimeString();  // -> "7:38:05 AM"

Documentation

Solution 3

2017 update: use toLocaleDateString and toLocaleTimeString to format dates and times. The first parameter passed to these methods is a locale value, such as en-us. The second parameter, where present, specifies formatting options, such as the long form for the weekday.

let date = new Date();  
let options = {  
    weekday: "long", year: "numeric", month: "short",  
    day: "numeric", hour: "2-digit", minute: "2-digit"  
};  

console.log(date.toLocaleTimeString("en-us", options)); 

Output : Wednesday, Oct 25, 2017, 8:19 PM

Please refer below link for more details.

Date and Time Strings (JavaScript)

Solution 4

You can use my port of strftime:

/* Port of strftime(). Compatibility notes:
 *
 * %c - formatted string is slightly different
 * %D - not implemented (use "%m/%d/%y" or "%d/%m/%y")
 * %e - space is not added
 * %E - not implemented
 * %h - not implemented (use "%b")
 * %k - space is not added
 * %n - not implemented (use "\n")
 * %O - not implemented
 * %r - not implemented (use "%I:%M:%S %p")
 * %R - not implemented (use "%H:%M")
 * %t - not implemented (use "\t")
 * %T - not implemented (use "%H:%M:%S")
 * %U - not implemented
 * %W - not implemented
 * %+ - not implemented
 * %% - not implemented (use "%")
 *
 * strftime() reference:
 * http://man7.org/linux/man-pages/man3/strftime.3.html
 *
 * Day of year (%j) code based on Joe Orost's answer:
 * http://stackoverflow.com/questions/8619879/javascript-calculate-the-day-of-the-year-1-366
 *
 * Week number (%V) code based on Taco van den Broek's prototype:
 * http://techblog.procurios.nl/k/news/view/33796/14863/calculate-iso-8601-week-and-year-in-javascript.html
 */
function strftime(sFormat, date) {
  if (!(date instanceof Date)) date = new Date();
  var nDay = date.getDay(),
    nDate = date.getDate(),
    nMonth = date.getMonth(),
    nYear = date.getFullYear(),
    nHour = date.getHours(),
    aDays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
    aMonths = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
    aDayCount = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334],
    isLeapYear = function() {
      if ((nYear&3)!==0) return false;
      return nYear%100!==0 || nYear%400===0;
    },
    getThursday = function() {
      var target = new Date(date);
      target.setDate(nDate - ((nDay+6)%7) + 3);
      return target;
    },
    zeroPad = function(nNum, nPad) {
      return ('' + (Math.pow(10, nPad) + nNum)).slice(1);
    };
  return sFormat.replace(/%[a-z]/gi, function(sMatch) {
    return {
      '%a': aDays[nDay].slice(0,3),
      '%A': aDays[nDay],
      '%b': aMonths[nMonth].slice(0,3),
      '%B': aMonths[nMonth],
      '%c': date.toUTCString(),
      '%C': Math.floor(nYear/100),
      '%d': zeroPad(nDate, 2),
      '%e': nDate,
      '%F': date.toISOString().slice(0,10),
      '%G': getThursday().getFullYear(),
      '%g': ('' + getThursday().getFullYear()).slice(2),
      '%H': zeroPad(nHour, 2),
      '%I': zeroPad((nHour+11)%12 + 1, 2),
      '%j': zeroPad(aDayCount[nMonth] + nDate + ((nMonth>1 && isLeapYear()) ? 1 : 0), 3),
      '%k': '' + nHour,
      '%l': (nHour+11)%12 + 1,
      '%m': zeroPad(nMonth + 1, 2),
      '%M': zeroPad(date.getMinutes(), 2),
      '%p': (nHour<12) ? 'AM' : 'PM',
      '%P': (nHour<12) ? 'am' : 'pm',
      '%s': Math.round(date.getTime()/1000),
      '%S': zeroPad(date.getSeconds(), 2),
      '%u': nDay || 7,
      '%V': (function() {
              var target = getThursday(),
                n1stThu = target.valueOf();
              target.setMonth(0, 1);
              var nJan1 = target.getDay();
              if (nJan1!==4) target.setMonth(0, 1 + ((4-nJan1)+7)%7);
              return zeroPad(1 + Math.ceil((n1stThu-target)/604800000), 2);
            })(),
      '%w': '' + nDay,
      '%x': date.toLocaleDateString(),
      '%X': date.toLocaleTimeString(),
      '%y': ('' + nYear).slice(2),
      '%Y': nYear,
      '%z': date.toTimeString().replace(/.+GMT([+-]\d+).+/, '$1'),
      '%Z': date.toTimeString().replace(/.+\((.+?)\)$/, '$1')
    }[sMatch] || sMatch;
  });
}

Sample usage:

// Returns "Thursday 4:45pm 15 Sep 2016"
strftime('%A %l:%M%P %e %b %Y');

// You can optionally pass it a Date object
// Returns "Friday 2:00pm 1 Feb 2013"
strftime('%A %l:%M%P %e %b %Y', new Date('Feb 1, 2013 2:00 PM'));

The latest code is available here: https://github.com/thdoan/strftime

Solution 5

Look at the internals of the Date class and you will see that you can extract all the bits (date, month, year, hour, etc).

http://www.w3schools.com/jsref/jsref_obj_date.asp

For something like Fri 23:00 1 Feb 2013 the code is like:

date = new Date();

weekdayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var dateString = weekdayNames[date.getDay()] + " " 
    + date.getHours() + ":" + ("00" + date.getMinutes()).slice(-2) + " " 
    + date.getDate() + " " + monthNames[date.getMonth()] + " " + date.getFullYear();

console.log(dateString);

**** Modified 2019-05-29 to keep 3 downvoters happy

Share:
444,889
Seong Lee
Author by

Seong Lee

I am a user interface designer based in New Zealand.

Updated on August 29, 2021

Comments

  • Seong Lee
    Seong Lee over 2 years

    I want to get current time in a specific format with javascript.

    With the function below and calling it will give me Fri Feb 01 2013 13:56:40 GMT+1300 (New Zealand Daylight Time) but I want to format it like Friday 2:00pm 1 Feb 2013

    var d = new Date();
    var x = document.getElementById("time");
    x.innerHTML = d;
    

    Of course, code above doesn't have any formatting logic but I have not come across with any "working" formatters yet.

  • gilly3
    gilly3 over 11 years
    w3schools is not great. See w3fools. Better reference sources include MDN and MSDN.
  • Seong Lee
    Seong Lee about 11 years
    Thanks a lot. Although my final code needed a bit of tweak, your insights helped.
  • afzalex
    afzalex over 9 years
    why your method is not working for me? d.toLocaleTimeString() and d.toLocaleTimeString() are not working.
  • Ye Lin Aung
    Ye Lin Aung over 9 years
    @afzalex you mean you aren't getting any return ?
  • afzalex
    afzalex over 9 years
    yes. I did not found any method toLocaleTimeString() and toLocaleTimeString()
  • blueberry0xff
    blueberry0xff over 8 years
    afzalex try this one: new Date().toLocaleString();
  • blueberry0xff
    blueberry0xff over 8 years
    console.log(new Date().toLocaleString()); // 9/27/2015, 2:52:18 PM
  • Vishal Singh
    Vishal Singh about 8 years
    How do i format date = "2016/03/01 11:00" to date ="Sat Mar 01 2016 11:00:00 GMT+0530 (IST)"
  • Vishal Singh
    Vishal Singh about 8 years
    How do i format date = "2016/03/01 11:00" to date ="Sat Mar 01 2016 11:00:00 GMT+0530 (IST)"
  • Ninjaxor
    Ninjaxor over 7 years
    Date#getDay returns an integer, not a name of weekday. Also, imho MDN does worse at getting the point across quickly regarding the Date object, so I don't understand why disparagement needs to take place.
  • shawon191
    shawon191 over 6 years
    Just wanted to mention, as of Oct 2017, moment is the current standard for time-related things in Javascript.
  • slf
    slf over 6 years
    thanks @shawon191 for the update :) ya, moment rocks. d3 has also added some time stuff too, so if you are already using that, you might be able to save a library import github.com/d3/d3/blob/master/API.md#time-formats-d3-time-for‌​mat
  • Sнаđошƒаӽ
    Sнаđошƒаӽ about 6 years
    Your answer in no way answers the OP.
  • Jochem Schulenklopper
    Jochem Schulenklopper about 6 years
    The problem with date.getMinutes() is that it returns a single digit when the minutes are less than 10, resulting in times like "10:4 am" instead of the more common "10:04 am".
  • Jochem Schulenklopper
    Jochem Schulenklopper about 6 years
    At this time - over four years after first answers to this question - this is now the most convenient and flexible solution, and answer to this question. It should be promoted higher as an example of current (AD 2018) practice :-)
  • purgatory101
    purgatory101 almost 6 years
    Worth noting that these methods can take the locale and options to allow even more flexibility. e.g. US with 24-hour time date.toLocaleTimeString('en-US', { hour12: false }); developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
  • PerpetualStudent
    PerpetualStudent over 5 years
    This is awesome. Thank you so much.
  • Weijing Jay Lin
    Weijing Jay Lin about 5 years
    What is checkTime function?
  • Lee Meador
    Lee Meador almost 5 years
    @JochemSchulenklopper Added the non-date code to display a leading zero on minutes
  • Lee Meador
    Lee Meador almost 5 years
    @Ninjaxor Added non-date related code to convert a number into a string. This should work if you want English names.
  • Jochem Schulenklopper
    Jochem Schulenklopper almost 5 years
    @LeeMeador, that's better. By the way, I didn't downvote your answer - I hardly downvote answers on SO. I just made a comment to inform people of a peculiarity that occurs in ten of the sixty minutes.
  • Alex Leo
    Alex Leo over 4 years
    Running the code gives an error:Uncaught TypeError: date.format is not a function
  • captain puget
    captain puget over 4 years
    Torn. @thdoan's port of strftime looks more flexible. For example, toLocalTimeString offers 4 date styles, full long medium short, and perhaps what those terms mean is defined somewhere. Meanwhile, strftime could (probably) match any of those and many more. On the other hand, toLocalTimeString supports time zones. I'm hoping that includes time zones that use daylight savings time...
  • Danegraphics
    Danegraphics about 4 years
    How does MMMM[0] return the correct month name instead of the non-printable character at index 0? Shouldn't it be MMMM[M]? Am I just dumb? (Nevermind. It sets it to the non-printable character, which it replaces later in order to avoid conflicts)
  • user3678915
    user3678915 over 3 years
    Perfect answer, which solves the whole problem.I think there is missing link to toLocaleString() where are described directly parameters and options
  • Joshua Pinter
    Joshua Pinter about 2 years
    Just a quick note that Moment has officially been deprecated. We still use it extensively and will continue to do so for the foreseeable but just a heads up.