Current time formatting with Javascript - 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.

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

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;
};

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)

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

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 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);

There are many great libraries out there, for those interested
http://www.datejs.com/
http://momentjs.com/
https://github.com/samsonjs/strftime
There really shouldn't be a need these days to invent your own formatting specifiers.

Using Moment.
I can't recommend the use of Moment enough. If you are able to use third-party libraries, I highly recommend doing so. Beyond just formatting, it deals with timezones, parsing, durations and time travel extremely well and will pay dividends in simplicity and time (at the small expense of size, abstraction and performance).
Usage
You wanted something that looked like this:
Friday 2:00pm 1 Feb 2013
Well, with Moment all you need you to do is this:
import Moment from "moment";
Moment().format( "dddd h:mma D MMM YYYY" ); //=> "Wednesday 9:20am 9 Dec 2020"
And if you wanted to match that exact date and time, all you would need to do is this:
import Moment from "moment";
Moment( "2013-2-1 14:00:00" ).format( "dddd h:mma D MMM YYYY" ) ); //=> "Friday 2:00pm 1 Feb 2013"
There's a myriad of other formatting options that can be found here.
Install
Go to their home page to see more detailed instructions, but if you're using npm or yarn it's as simple as:
npm install moment --save
or
yarn add moment

Only time
const getTime = ()=>{
const d = new Date();
const dd = [d.getHours(), d.getMinutes(), d.getSeconds()].map((a)=>(a < 10 ? '0' + a : a));
return dd.join(':');
};

d = Date.now();
d = new Date(d);
d = (d.getMonth()+1)+'/'+d.getDate()+'/'+d.getFullYear()+' '+(d.getHours() > 12 ? d.getHours() - 12 : d.getHours())+':'+d.getMinutes()+' '+(d.getHours() >= 12 ? "PM" : "AM");
console.log(d);

For this true mysql style use this function below: 2019/02/28 15:33:12
If you click the
'Run code snippet' button below
It will show your an simple realtime digital clock example
The demo will appear below the code snippet.
function getDateTime() {
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth()+1;
var day = now.getDate();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
if(month.toString().length == 1) {
month = '0'+month;
}
if(day.toString().length == 1) {
day = '0'+day;
}
if(hour.toString().length == 1) {
hour = '0'+hour;
}
if(minute.toString().length == 1) {
minute = '0'+minute;
}
if(second.toString().length == 1) {
second = '0'+second;
}
var dateTime = year+'/'+month+'/'+day+' '+hour+':'+minute+':'+second;
return dateTime;
}
// example usage: realtime clock
setInterval(function(){
currentTime = getDateTime();
document.getElementById("digital-clock").innerHTML = currentTime;
}, 1000);
<div id="digital-clock"></div>

2.39KB minified. One file. https://github.com/rhroyston/clock-js
Current Time is
var str = clock.month;
var m = str.charAt(0).toUpperCase() + str.slice(1,3); //gets you abbreviated month
clock.weekday + ' ' + clock.time + ' ' + clock.day + ' ' + m + ' ' + clock.year; //"tuesday 5:50 PM 3 May 2016"

function formatTime(date){
d = new Date(date);
var h=d.getHours(),m=d.getMinutes(),l="AM";
if(h > 12){
h = h - 12;
}
if(h < 10){
h = '0'+h;
}
if(m < 10){
m = '0'+m;
}
if(d.getHours() >= 12){
l="PM"
}else{
l="AM"
}
return h+':'+m+' '+l;
}
Usage & result:
var formattedTime=formatTime(new Date('2020 15:00'));
// Output: "03:00 PM"

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.).

This is not exactly what you asked but maybe something here can help.
const dateToday = new Date();
const weekDay = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
let day = weekDay[dateToday.getDay()];
let hr = [dateToday.getHours()% 12 || 12];
let min = [dateToday.getMinutes()];
let sec = [dateToday.getSeconds()];
document.getElementById("date").innerHTML = "Today is: " + day;
var amPm;
if (hr > 12){
amPm = "AM"
} else {
amPm = "PM"
}
document.getElementById("time").innerHTML = "Current time is: " + hr + ":" + min + ":" + sec + " " + amPm;
<div>
<p id="date"></p>
<p id="time"></p>
</div>

function startTime() {
var today = new Date(),
h = checkTime(((today.getHours() + 11) % 12 + 1)),
m = checkTime(today.getMinutes()),
s = checkTime(today.getSeconds());
document.getElementById('demo').innerHTML = h + ":" + m + ":" + s;
t = setTimeout(function () {
startTime()
}, 500);
}
startTime();
})();
05:12:00

let date = new Date();
let time = date.format("hh:ss")

Related

How to Get the current Time in "29 Aug 2018 3:12:32 PM IST" format using Javascript? [duplicate]

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.
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
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;
};
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)
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
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 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);
There are many great libraries out there, for those interested
http://www.datejs.com/
http://momentjs.com/
https://github.com/samsonjs/strftime
There really shouldn't be a need these days to invent your own formatting specifiers.
Using Moment.
I can't recommend the use of Moment enough. If you are able to use third-party libraries, I highly recommend doing so. Beyond just formatting, it deals with timezones, parsing, durations and time travel extremely well and will pay dividends in simplicity and time (at the small expense of size, abstraction and performance).
Usage
You wanted something that looked like this:
Friday 2:00pm 1 Feb 2013
Well, with Moment all you need you to do is this:
import Moment from "moment";
Moment().format( "dddd h:mma D MMM YYYY" ); //=> "Wednesday 9:20am 9 Dec 2020"
And if you wanted to match that exact date and time, all you would need to do is this:
import Moment from "moment";
Moment( "2013-2-1 14:00:00" ).format( "dddd h:mma D MMM YYYY" ) ); //=> "Friday 2:00pm 1 Feb 2013"
There's a myriad of other formatting options that can be found here.
Install
Go to their home page to see more detailed instructions, but if you're using npm or yarn it's as simple as:
npm install moment --save
or
yarn add moment
Only time
const getTime = ()=>{
const d = new Date();
const dd = [d.getHours(), d.getMinutes(), d.getSeconds()].map((a)=>(a < 10 ? '0' + a : a));
return dd.join(':');
};
d = Date.now();
d = new Date(d);
d = (d.getMonth()+1)+'/'+d.getDate()+'/'+d.getFullYear()+' '+(d.getHours() > 12 ? d.getHours() - 12 : d.getHours())+':'+d.getMinutes()+' '+(d.getHours() >= 12 ? "PM" : "AM");
console.log(d);
For this true mysql style use this function below: 2019/02/28 15:33:12
If you click the
'Run code snippet' button below
It will show your an simple realtime digital clock example
The demo will appear below the code snippet.
function getDateTime() {
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth()+1;
var day = now.getDate();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
if(month.toString().length == 1) {
month = '0'+month;
}
if(day.toString().length == 1) {
day = '0'+day;
}
if(hour.toString().length == 1) {
hour = '0'+hour;
}
if(minute.toString().length == 1) {
minute = '0'+minute;
}
if(second.toString().length == 1) {
second = '0'+second;
}
var dateTime = year+'/'+month+'/'+day+' '+hour+':'+minute+':'+second;
return dateTime;
}
// example usage: realtime clock
setInterval(function(){
currentTime = getDateTime();
document.getElementById("digital-clock").innerHTML = currentTime;
}, 1000);
<div id="digital-clock"></div>
2.39KB minified. One file. https://github.com/rhroyston/clock-js
Current Time is
var str = clock.month;
var m = str.charAt(0).toUpperCase() + str.slice(1,3); //gets you abbreviated month
clock.weekday + ' ' + clock.time + ' ' + clock.day + ' ' + m + ' ' + clock.year; //"tuesday 5:50 PM 3 May 2016"
function formatTime(date){
d = new Date(date);
var h=d.getHours(),m=d.getMinutes(),l="AM";
if(h > 12){
h = h - 12;
}
if(h < 10){
h = '0'+h;
}
if(m < 10){
m = '0'+m;
}
if(d.getHours() >= 12){
l="PM"
}else{
l="AM"
}
return h+':'+m+' '+l;
}
Usage & result:
var formattedTime=formatTime(new Date('2020 15:00'));
// Output: "03:00 PM"
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.).
This is not exactly what you asked but maybe something here can help.
const dateToday = new Date();
const weekDay = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
let day = weekDay[dateToday.getDay()];
let hr = [dateToday.getHours()% 12 || 12];
let min = [dateToday.getMinutes()];
let sec = [dateToday.getSeconds()];
document.getElementById("date").innerHTML = "Today is: " + day;
var amPm;
if (hr > 12){
amPm = "AM"
} else {
amPm = "PM"
}
document.getElementById("time").innerHTML = "Current time is: " + hr + ":" + min + ":" + sec + " " + amPm;
<div>
<p id="date"></p>
<p id="time"></p>
</div>
function startTime() {
var today = new Date(),
h = checkTime(((today.getHours() + 11) % 12 + 1)),
m = checkTime(today.getMinutes()),
s = checkTime(today.getSeconds());
document.getElementById('demo').innerHTML = h + ":" + m + ":" + s;
t = setTimeout(function () {
startTime()
}, 500);
}
startTime();
})();
05:12:00
let date = new Date();
let time = date.format("hh:ss")

how to get time with some specific format?

how should i getTime with some specific format like i want to get time hh:mm am/pm and then add some minute .
example i have date 2016-09-16T11:40:50.000Z from it first get time 11:40 am and then add 20 minutes and get result like 12:00 am
so, how can i do this task.
i try date.getTime() but it not give me proper time which i want.
function gettime(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
return = hours + ':' + minutes + ' ' + ampm;
}
for adding more minutes you can use
date.getMinutes() + 20; //It will add 20 minutes
If you're talking about Date.prototype.getTime() function then there is no direct way to a formated string using this function because it always returns integer that mean seconds.
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;
};

Convert current date to specific format using jquery/javascript [duplicate]

This question already has answers here:
How do I format a date in JavaScript?
(68 answers)
Closed 7 years ago.
I want to convert the current date (2016-1-12) to following format.
Tuesday 12th of January 2016 11:52:00 AM
How to do that using using jquery/javascript?
Well, I want to remmend use libraries to work with date / time, but if you want it on pure JS solution is something like this:
var date = new Date(2016-1-12),
dayOfWeekName = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],
monthName = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
function ordinal_suffix_of(i) {
var j = i % 10,
k = i % 100;
if (j == 1 && k != 11) {
return i + "st";
}
if (j == 2 && k != 12) {
return i + "nd";
}
if (j == 3 && k != 13) {
return i + "rd";
}
return i + "th";
}
var formattedDate = dayOfWeekName[date.getDay()] + ' ' + date.getDate() + ordinal_suffix_of(date.getDate()) + ' ' + monthName[date.getMonth()] + ' ' + date.getFullYear() + ' ' + date.toLocaleTimeString('en-US');
Great question! Javascript does not play with dates as nicely as other languages in my experience. Here is some great code that will do what you are asking for.
/*
* Date Format 1.2.3
* (c) 2007-2009 Steven Levithan <stevenlevithan.com>
* MIT license
*
* Includes enhancements by Scott Trenda <scott.trenda.net>
* and Kris Kowal <cixar.com/~kris.kowal/>
*
* Accepts a date, a mask, or a date and a mask.
* Returns a formatted version of the given date.
* The date defaults to the current date/time.
* The mask defaults to dateFormat.masks.default.
*/
var dateFormat = function () {
var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
timezoneClip = /[^-+\dA-Z]/g,
pad = function (val, len) {
val = String(val);
len = len || 2;
while (val.length < len) val = "0" + val;
return val;
};
// Regexes and supporting functions are cached through closure
return function (date, mask, utc) {
var dF = dateFormat;
// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
mask = date;
date = undefined;
}
// Passing date through Date applies Date.parse, if necessary
date = date ? new Date(date) : new Date;
if (isNaN(date)) throw SyntaxError("invalid date");
mask = String(dF.masks[mask] || mask || dF.masks["default"]);
// Allow setting the utc argument via the mask
if (mask.slice(0, 4) == "UTC:") {
mask = mask.slice(4);
utc = true;
}
var _ = utc ? "getUTC" : "get",
d = date[_ + "Date"](),
D = date[_ + "Day"](),
m = date[_ + "Month"](),
y = date[_ + "FullYear"](),
H = date[_ + "Hours"](),
M = date[_ + "Minutes"](),
s = date[_ + "Seconds"](),
L = date[_ + "Milliseconds"](),
o = utc ? 0 : date.getTimezoneOffset(),
flags = {
d: d,
dd: pad(d),
ddd: dF.i18n.dayNames[D],
dddd: dF.i18n.dayNames[D + 7],
m: m + 1,
mm: pad(m + 1),
mmm: dF.i18n.monthNames[m],
mmmm: dF.i18n.monthNames[m + 12],
yy: String(y).slice(2),
yyyy: y,
h: H % 12 || 12,
hh: pad(H % 12 || 12),
H: H,
HH: pad(H),
M: M,
MM: pad(M),
s: s,
ss: pad(s),
l: pad(L, 3),
L: pad(L > 99 ? Math.round(L / 10) : L),
t: H < 12 ? "a" : "p",
tt: H < 12 ? "am" : "pm",
T: H < 12 ? "A" : "P",
TT: H < 12 ? "AM" : "PM",
Z: utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
o: (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
S: ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
};
return mask.replace(token, function ($0) {
return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
});
};
}();
// Some common format strings
dateFormat.masks = {
"default": "ddd mmm dd yyyy HH:MM:ss",
shortDate: "m/d/yy",
mediumDate: "mmm d, yyyy",
longDate: "mmmm d, yyyy",
fullDate: "dddd, mmmm d, yyyy",
shortTime: "h:MM TT",
mediumTime: "h:MM:ss TT",
longTime: "h:MM:ss TT Z",
isoDate: "yyyy-mm-dd",
isoTime: "HH:MM:ss",
isoDateTime: "yyyy-mm-dd'T'HH:MM:ss",
isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};
// Internationalization strings
dateFormat.i18n = {
dayNames: [
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
],
monthNames: [
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
]
};
// For convenience...
Date.prototype.format = function (mask, utc) {
return dateFormat(this, mask, utc);
};
My proposal is:
function formatDate(dateStr) {
var daysOfWeek = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var monthOfYear = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
var myDate = new Date(dateStr);
var hours = myDate.getHours();
var mid='am';
if (hours == 0){
hours=12;
} else {
if (hours > 12) {
hours = hours % 12;
mid='pm';
}
if (hours < 10) {
hours = '0' + hours;
}
}
var minutes = myDate.getMinutes();
if (minutes < 10) {
minutes = '0' + minutes;
}
var seconds = myDate.getSeconds();
if (seconds < 10) {
seconds = '0' + seconds;
}
return daysOfWeek[myDate.getDay()] + ' ' + myDate.getDate() + 'th ' + monthOfYear[myDate.getMonth()] + ' ' + myDate.getFullYear() +
' ' + hours + ':' + minutes + ':' + seconds + ' ' + mid;
}
alert(formatDate('2016-1-12 22:40:01'));

Javascript to display the current date and time

I have the following test Script to display the current date & time :-
document.getElementById("para1").innerHTML = formatAMPM();
function formatAMPM() {
var date = new Date();
var hours = date.getHours();
var days = date.getDay();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = date + ' ' + hours + ':' + minutes + ' ' + ampm;
return strTime;
}
which will display the following :-
Fri Aug 30 2013 16:36:10 GMT+0100 (GMT Standard Time) 4:36 pm
but i need to modify this to display only:-
Fri Aug 30 2013 4:36 pm
can anyone advice on how i can achieve this ?
Demo using Console.Log
// get a new date (locale machine date time)
var date = new Date();
// get the date as a string
var n = date.toDateString();
// get the time as a string
var time = date.toLocaleTimeString();
// log the date in the browser console
console.log('date:', n);
// log the time in the browser console
console.log('time:',time);
Demo using a DIV
// get a new date (locale machine date time)
var date = new Date();
// get the date as a string
var n = date.toDateString();
// get the time as a string
var time = date.toLocaleTimeString();
// find the html element with the id of time
// set the innerHTML of that element to the date a space the time
document.getElementById('time').innerHTML = n + ' ' + time;
<div id='time'></div>
Note: these functions aren't fully cross browser supported
Cross-Browser Functional
//Fri Aug 30 2013 4:36 pm
console.log(formatAMPM(new Date()));
//using your function (passing in date)
function formatAMPM(date) {
// gets the hours
var hours = date.getHours();
// gets the day
var days = date.getDay();
// gets the month
var minutes = date.getMinutes();
// gets AM/PM
var ampm = hours >= 12 ? 'pm' : 'am';
// converts hours to 12 hour instead of 24 hour
hours = hours % 12;
// converts 0 (midnight) to 12
hours = hours ? hours : 12; // the hour '0' should be '12'
// converts minutes to have leading 0
minutes = minutes < 10 ? '0'+ minutes : minutes;
// the time string
var time = hours + ':' + minutes + ' ' + ampm;
// gets the match for the date string we want
var match = date.toString().match(/\w{3} \w{3} \d{1,2} \d{4}/);
//the result
return match[0] + ' ' + time;
}
Try this:
var d = new Date(),
minutes = d.getMinutes().toString().length == 1 ? '0'+d.getMinutes() : d.getMinutes(),
hours = d.getHours().toString().length == 1 ? '0'+d.getHours() : d.getHours(),
ampm = d.getHours() >= 12 ? 'pm' : 'am',
months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],
days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
return days[d.getDay()]+' '+months[d.getMonth()]+' '+d.getDate()+' '+d.getFullYear()+' '+hours+':'+minutes+ampm;
DEMO
Updated to use the more modern Luxon instead of MomentJS.
Don't reinvent the wheel. Use a tried and tested library do this for you, Luxon for example: https://moment.github.io/luxon/index.html
From their site:
https://moment.github.io/luxon/docs/class/src/datetime.js~DateTime.html#instance-method-toLocaleString
//=> 'Thu, Apr 20, 11:27 AM'
DateTime.local().toLocaleString({ weekday: 'short', month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit' });
(function(con) {
var oDate = new Date();
var nHrs = oDate.getHours();
var nMin = oDate.getMinutes();
var nDate = oDate.getDate();
var nMnth = oDate.getMonth();
var nYear = oDate.getFullYear();
con.log(nDate + ' - ' + nMnth + ' - ' + nYear);
con.log(nHrs + ' : ' + nMin);
})(console);
This produces an output like:
30 - 8 - 2013
21 : 30
Perhaps you may refer documentation on Date object at MDN for more information
You can try the below:
function formatAMPM() {
var date = new Date();
var currDate = date.getDate();
var hours = date.getHours();
var dayName = getDayName(date.getDay());
var minutes = date.getMinutes();
var monthName = getMonthName(date.getMonth());
var year = date.getFullYear();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0' + minutes : minutes;
var strTime = dayName + ' ' + monthName + ' ' + currDate + ' ' + year + ' ' + hours + ':' + minutes + ' ' + ampm;
alert(strTime);
}
function getMonthName(month) {
var ar = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
return ar[month];
}
function getDayName(day) {
var ar1 = new Array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
return ar1[day];
}
EDIT: Refer here for a working demo.
(new Date()).toLocaleString()
Will output the date and time using your local format. For example: "5/1/2020, 10:35:41 AM"
The request was to format a date in this format:
Fri Aug 30 2013 4:36 pm
I strongly suggest that anyone who comes across this question should use JavaScript's Intl API to format your dates instead of trying to come up with your own preferred format.
Here's an example
let d = new Date();
let formatter = Intl.DateTimeFormat(
"default", // a locale name; "default" chooses automatically
{
weekday: "short",
year: "numeric",
month: "short",
day: "numeric",
hour: "numeric",
minute: "numeric"
}
);
console.log(formatter.format(d));
The output for me, in the en-US locale, is:
Wed, Sep 30, 2020, 5:04 PM
The output for someone in Mexico (es-MX), is:
miƩ., 30 de septiembre de 2020 17:23
Why is Intl better?
It's native code, with no string manipulation, no extra frameworks required, just a browser from any time after 2013 (when this question was first posted)
Nothing to download
No frameworks to add
Native code runs faster
Intl formats dates as appropriate for the user's locale, e.g. a user in a different country who would prefer to read the year before the month would see the appropriately formatted date
Get the data you need and combine it in the String;
getDate(): Returns the date
getMonth(): Returns the month
getFullYear(): Returns the year
getHours();
getMinutes();
Check out : Working With Dates
To return the client side date you can use the following javascript:
var d = new Date();
var month = d.getMonth()+1;
var date = d.getDate()+"."+month+"."+d.getFullYear();
document.getElementById('date').innerHTML = date;
or in jQuery:
var d = new Date();
var month = d.getMonth()+1;
var date = d.getDate()+"."+month+"."+d.getFullYear();
$('#date').html(date);
equivalent to following PHP:
<?php date("j.n.Y"); ?>
To get equivalent to the following PHP (i.e. leading 0's):
<?php date("d.m.Y"); ?>
JavaScript:
var d = new Date();
var day = d.getDate();
var month = d.getMonth()+1;
if(day < 10){
day = "0"+d.getDate();
}
if(month < 10){
month = "0"+eval(d.getMonth()+1);
}
var date = day+"."+month+"."+d.getFullYear();
document.getElementById('date').innerHTML = date;
jQuery:
var d = new Date();
var day = d.getDate();
var month = d.getMonth()+1;
if(day < 10){
day = "0"+d.getDate();
}
if(month < 10){
month = "0"+eval(d.getMonth()+1);
}
var date = day+"."+month+"."+d.getFullYear();
$('#date').html(date);
<!-- //Hide From Old Browsers
var d=new Date();
var y=d.getYear();
if (y < 1000)
y+=1900;
var day=d.getDay();
var m=d.getMonth();
var daym=d.getDate();
if (daym<10)
daym="0"+daym;
var mon=new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
document.write("<font size='2' color='#660000'>"+mon[m]+" "+daym+", "+y+"</font>");
// End Hide -->
Result : November 08, 2014
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1;//January is 0!
var yyyy = today.getFullYear();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
if(dd<10){dd='0'+dd}
if(mm<10){mm='0'+mm}
if(h<10){h='0'+h}
if(m<10){m='0'+m}
if(s<10){s='0'+s}
onload = function(){
$scope.currentTime=+dd+'/'+mm+'/'+yyyy+' '+h+':'+m+':'+s;
}
var today = new Date();
var day = today.getDay();
var daylist = ["Sunday", "Monday", "Tuesday", "Wednesday ", "Thursday", "Friday", "Saturday"];
console.log("Today is : " + daylist[day] + ".");
var hour = today.getHours();
var minute = today.getMinutes();
var second = today.getSeconds();
var prepand = (hour >= 12) ? " PM " : " AM ";
hour = (hour >= 12) ? hour - 12 : hour;
if (hour === 0 && prepand === ' PM ') {
if (minute === 0 && second === 0) {
hour = 12;
prepand = ' Noon';
} else {
hour = 12;
prepand = ' PM';
}
}
if (hour === 0 && prepand === ' AM ') {
if (minute === 0 && second === 0) {
hour = 12;
prepand = ' Midnight';
} else {
hour = 12;
prepand = ' AM';
}
}
console.log("Current Time : " + hour + prepand + " : " + minute + " : " + second);
<script>
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1; //January is 0!
var yyyy = today.getFullYear();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
if (dd < 10) {
dd = '0' + dd
}
if (mm < 10) {
mm = '0' + mm
}
if (h < 10) { h = '0' + h }
if (m < 10) { m = '0' + m }
if (s < 10) { s = '0' + s }
var ctoday = dd + '/' + mm + '/' + yyyy+ '\t' +h+ ':' +m+ ':' +s;
var d = new Date()
var weekday = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")
console.log("Today is " + weekday[d.getDay()])
document.getElementById('time').innerHTML = '<span style="color:blue">' + weekday[d.getDay()] + ", " + ctoday + '</span>';
</script>
<div>
<span> Today is : <span id="time"> </span>
</div>
function showTime(){
let date = new Date();
let h = date.getHours();
let m = date.getMinutes();
let s = date.getSeconds();
let d = date.getDate() ;
let month = date.getMonth()+1;
let year = date.getFullYear();
let session = "AM";
if(h == 0){
h = 12;
}
if(h > 12){
h = h - 12;
session = "PM";
}
h = (h < 10) ? "0" + h : h;
m = (m < 10) ? "0" + m : m;
s = (s < 10) ? "0" + s : s;
d = (d < 10) ? "0" + d : d;
//Adds zero when less than 10.
month = (month < 10) ? "0" + month : month;

Javascript: how to format a given datetime?

given my data is:
2011-12-31 01:00:00
what easy and quick script can I use to exctract simply: "DEC 31" ?
Create the following helper functions:
function getMonthName(d) {
var m = ['January','February','March','April','May','June','July',
'August','September','October','November','December'];
return m[d.getMonth()];
}
function getShortMonthName(d) {
return getMonthName(d).substring(0, 3).toUpperCase();
}
And use them like this:
var s = "2011-12-31 01:00:00".split(/-|\s+|:/);
// new Date(year, month, day [, hour, minute, second, millisecond ])
var d = new Date(s[0], s[1] - 1, s[2], s[3], s[4], s[5]);
getShortMonthName(d) + " " + d.getDate();
Output:
"DEC 31"
http://www.datejs.com/ is nice for this
Using it the code would be like (tested and works)
Date.parse('2011-12-31 01:00:00').toString("MMM d"); // "Dec 31"
This solution is wonderful because datajs is a very flexible library.
This can do it. Just pass the string as a parameter to the date object and split the dateString. Concatenate and you're done :)
var n = new Date("2011-12-31 01:00:00");
var d = n.toDateString().split(" ");
var formattedDate = d[1].toUpperCase() + " " + d[2];
or optionally as a function
function getFormattedDate(dateString) {
var n = new Date(dateString);
var d = n.toDateString().split(" ");
return d[1].toUpperCase() + " " + d[2];
}
var formattedDate = getFormattedDate("2011-12-31 01:00:00"); // returns "DEC 31"
A function that would do exactly what you asked for (and nothing more):
function toMonthAndDay(dateString) {
var months = ['JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC'];
var dateParts = dateString.split(/[- ]/);
return months[+dateParts[1]] + " " + dateParts[2];
}
But, to take any date and output it in any custom format, I wrote a function that is loosely based on .Net DateTime format strings:
Date.prototype.format = function (format)
{
var MMMM = ["\u0000", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var MMM = ["\u0001", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var dddd = ["\u0002", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
var ddd = ["\u0003", "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 = this.getFullYear();
format = format.replace(/yyyy+/g, y);
format = format.replace(/yy/g, y.toString().substr(2, 2));
format = format.replace(/y/g, y);
var M = this.getMonth() + 1;
format = format.replace(/MMMM+/g, MMMM[0]);
format = format.replace(/MMM/g, MMM[0]);
format = format.replace(/MM/g, ii(M));
format = format.replace(/M/g, M);
var d = this.getDate();
format = format.replace(/dddd+/g, dddd[0]);
format = format.replace(/ddd/g, ddd[0]);
format = format.replace(/dd/g, ii(d));
format = format.replace(/d/g, d);
var H = this.getHours();
format = format.replace(/HH+/g, ii(H));
format = format.replace(/H/g, H);
var h = H > 12 ? H - 12 : H == 0 ? 12 : H;
format = format.replace(/hh+/g, ii(h));
format = format.replace(/h/g, h);
var m = this.getMinutes();
format = format.replace(/mm+/g, ii(m));
format = format.replace(/m/g, m);
var s = this.getSeconds();
format = format.replace(/ss+/g, ii(s));
format = format.replace(/s/g, s);
var f = this.getMilliseconds();
format = format.replace(/fff+/g, ii(f, 3));
f = Math.round(f / 10);
format = format.replace(/ff/g, ii(f));
f = Math.round(f / 10);
format = format.replace(/f/g, f);
var T = H < 12 ? "AM" : "PM";
format = format.replace(/TT+/g, T);
format = format.replace(/T/g, T.charAt(0));
var t = T.toLowerCase();
format = format.replace(/tt+/g, t);
format = format.replace(/t/g, t.charAt(0));
var day = this.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]);
return format;
};
Usage:
new Date("2011-12-31 01:00:00".replace(/-/g, "/")).format("MMM d"); // returns Dec 31
Note that IE doesn't recognize "2011-12-31 01:00:00" as a valid date string. You have to replace the dashes with slashes. To get DEC instead of Dec, you'd have to call .toUpperCase().
The differences from .Net custom date format strings are:
You can make AM/PM uppercase or lowercase by using TT or tt respectively
Using \ as an escape character is not (yet) implemented.
This should work:
var date = "2011-12-31 01:00:00";
var day = date.substring(8, 10);
var month = parseInt(date.substring(5, 7));
switch(month) {
case 1: month="JAN";break;
case 2: month="FEB";break;
case 3: month="MAR";break;
case 4: month="APR";break;
case 5: month="MAY";break;
case 6: month="JUN";break;
case 7: month="JUL";break;
case 8: month="AUG";break;
case 9: month="SEP";break;
case 10: month="OCT";break;
case 11: month="NOV";break;
case 12: month="DEC";break;
}
alert(month + " " + day);

Categories

Resources