Wednesday, September 9, 2015

Current time formatting with Javascript


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.
shareimprove this question

5 Answers

up vote32down voteaccepted
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 d = new Date();
var day = days[d.getDay()];
var hr = d.getHours();
var min = d.getMinutes();
if (min < 10) {
    min = "0" + min;
}
var ampm = hr < 12 ? "am" : "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;
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");
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;
};
shareimprove this answer
   
Thanks a lot. Although my final code needed a bit of tweak, your insights helped. –  Seong Lee May 7 '13 at 21:22
You may want to try
d = new Date();
d.toLocaleString();       // -> "2/1/2013 7:37:08 AM"
d.toLocaleDateString();   // -> "2/1/2013"
d.toLocaleTimeString();  // -> "7:38:05 AM"
shareimprove this answer
   
why your method is not working for me? d.toLocaleTimeString() and d.toLocaleTimeString() are not working. –  afzalex Oct 9 '14 at 16:55
   
@afzalex you mean you aren't getting any return ? –  Ye Lin Aung Oct 10 '14 at 11:03
   
yes. I did not found any method toLocaleTimeString() and toLocaleTimeString() –  afzalex Oct 10 '14 at 22:28
Look at the internals of the Date class and you will see that you can extract all the bits (date, month, year, hour, etc).
For something like Friday 2:00pm 1 Feb 2013 the code is sort of like:
var dateString = date.getDay() + " " + date.getHours() + ":" + date.getMinutes() ...
shareimprove this answer
7 
w3schools is not great. See w3fools. Better reference sources include MDN and MSDN. –  gilly3 Feb 1 '13 at 1:10
To work with the base Date class you can look at MDN for its methods (instead of W3Schools due tothis reason). There you can find a good description about every method useful to access each single date/time component and informations relative to whether a method is deprecated or not.
Otherwise you can look at Moment.js that is a good library to use for date and time processing. You can use it to manipulate date and time (such as parsing, formatting, i18n, etc.).
shareimprove this answer
There are many great libraries out there, for those interested
There really shouldn't be a need these days to invent your own formatting specifiers. I would go with strftime as it's the most standard.
shareimprove this answer http://stackoverflow.com/questions/14638018/current-time-formatting-with-javascript