14
6
|
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
Of course, code above doesn't have any formatting logic but I have not come across with any "working" formatters yet.
| |||
add a comment
|
32
|
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:
"dddd h:mmtt d MMM yyyy" .
Demo: jsfiddle.net/BNkkB/1
Here is my full date formatting function:
| ||||
|
29
|
You may want to try
| ||||||||||||
|
2
|
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:
| ||||
|
0
|
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.).
| ||
0
|
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.
|