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.
A JavaScript Date has several methods allowing you to extract its parts:
getFullYear()
- Returns the 4-digit yeargetMonth()
- 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:
Then, put it together using the methods above:
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:
"ffffdd h:mmtt d MMM yyyy"
.Demo: jsfiddle.net/BNkkB/1
Here is my full date formatting function:
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
Friday 2:00pm 1 Feb 2013
the code is sort of like:})();
05:12:00
For time I mostly 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.
Please refer below link for more details.
Date and Time Strings (JavaScript)
To work with the base Date class you can look at MDN for its methods (instead of W3Schools due to this 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.).
2.39KB minified. One file. https://github.com/rhroyston/clock-js
Current Time is