get current date in this format "May 09, 2019" - javascript

i want to get the current time in May 09, 2019 format.
var d = new Date();
var delay = 500;
var month = d.getMonth()+1;
var day = d.getDate();
var y=d.getFullYear();
var output = d.getFullYear() + '/' +
((''+month).length<2 ? '0' : '') + month + '/' +
((''+day).length<2 ? '0' : '') + day;
here the output shows the current time in 2019/05/09 format.how should i get "May 05, 2019" format.

Try this
var d = new Date();
var months = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
var month = months[d.getMonth()]
var day = d.getDate();
var y=d.getFullYear();
var today = month +" " +day + "," + y;
console.log(today);

Instead of creating (and maintain) your own array of names you can use the following:
d.toLocaleString('en-us', { month: 'long' });
var d = new Date();
var month = d.toLocaleString('en-us', { month: 'long' });
var day = d.getDate();
var y=d.getFullYear();
var today = month +" " +day + "," + y;
console.log(today);

You can do this,
var monthNames = [
"Jan", "Feb", "Mar",
"Apr", "May", "Jun", "Jul",
"Aug", "Sep", "Oct",
"Nov", "Dec"
];
var d = new Date();
var day = d.getDate();
var monthIndex = d.getMonth();
var year = d.getFullYear();
var output = monthNames[monthIndex] + ' 'day + ' ,' + year;

This is exactly what you are looking for
function LogCurrentDate(e){
var date = new Date();
var options = { year: 'numeric', month: 'long', day: '2-digit' };
$(".output").empty().append("<p>" + date.toLocaleDateString('en-US', options) + "</p>");
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<button onclick="LogCurrentDate(event)">Show Date</button>
</div>
<div class="output"></div>

Related

How to turn a period of date into an array?

How to turn a period of date in an array? For example, I have a period of date from 1 March 2020 to 29 April 2020, how can I turn it into an array shown below?
period = [{day: "Sun", date: "1", month: "Mar", year: "2020"}, ...,
{day: "Wed",date: "29", month: "Apr", year: "2020"}]
You can create array from date range follow https://stackoverflow.com/a/50398144/4964569
and get day in date follow https://stackoverflow.com/a/4822882/4964569
And use map function to generate your required
var getDaysArray = function(s,e) {for(var a=[],d=new Date(s);d<=e;d.setDate(d.getDate()+1)){ a.push(new Date(d));}return a;};
var dateRange = getDaysArray(new Date('2020-03-10'), new Date('2020-04-29'));
var days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
var result = dateRange.map(function(elem){
var obj = {
day: days[elem.getDay()],
date: elem.getDate(),
month: elem.getMonth(),
year: elem.getFullYear()
}
return obj;
});
console.log(result)
var getDaysArray = function(s,e) {for(var a=[],d=new Date(s);d<=e;d.setDate(d.getDate()+1)){ a.push(new Date(d));}return a;};
var dateRange = getDaysArray(new Date('2020-03-10'), new Date('2020-04-29'));
var days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
var result = dateRange.map(function(elem){
var obj = {
day: days[elem.getDay()],
date: elem.getDate(),
month: elem.getMonth(),
year: elem.getFullYear()
}
return obj;
});
console.log(result)
In traditional way you can do it like this
var startDate = new Date('2020-03-10');
var endDateDate = new Date('2020-03-12');
var arr = [];
var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
while(startDate.getTime() !== endDateDate.getTime()) {
startDate.setDate(startDate.getDate() + 1)
arr.push({
day: days[startDate.getDay()],
date: startDate.getDate(),
month: startDate.getMonth(),
year: startDate.getYear()
})
}
console.log(arr);
I'm assuming you have two Dates as your range delimiters. If not, you can create them this way:
var startDate = new Date('1 March 2020')
var endDate = new Date('29 April 2020')
Then, you have to increase the first date by one day until you reach the last date. To increase the first date by one day you can do this:
startDate.setDate(startDate.getDate() + 1)
You can get the day and the month from a Date with date.getDay() and date.getMonth(), but those methods will return numbers. To get the actual names you can do this:
var days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
var startDateDay = days[startDate.getDay()]
var startDateMonth = months[startDate.getMonth()]
And then, you iterate:
var period = []
while (startDate <= lastDate) {
period.push({
day: days[startDate.getDay()],
date: startDate.getDate(),
month: months[startDate.getMonth()],
year: startDate.getYear()
})
startDate.setDate(startDate.getDate() + 1)
}
And that's it. Here's a fiddle with a working example:
var startDate = new Date('1 March 2020')
var endDate = new Date('29 April 2020')
var days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
var period = []
while (startDate <= endDate) {
period.push({
day: days[startDate.getDay()],
date: startDate.getDate(),
month: months[startDate.getMonth()],
year: startDate.getFullYear()
})
startDate.setDate(startDate.getDate() + 1)
}
console.log(period)
var start = new Date('March 1, 2020');
var period = [];
for(var i=1; i<=60; i++){
if( i == 32 )
start = new Date('April 1, 2020');
if( i <= 31 )
start.setDate(i);
else
start.setDate(i - 31);
var dateString = start.toDateString().split(' ');
period.push({
day: dateString[0],
date: dateString[2],
month: dateString[1],
year: dateString[3]
});
}
console.log( JSON.stringify(period) );

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

Stackoverflow style date format

How to format the javascript Date object the way stackoverflow does it.
For example. Aug 23 '10 at 23:35
This is what I tried.
new Date(val.replace(' ','T')+'Z').toString().split('GMT')[0]
This works cross browser. But doesn't look neat.
function formatDate(date) {
var monthNames = [
"Jan", "Feb", "Mar",
"Apr", "May", "Jun", "Jul",
"Aug", "Sep", "Oct",
"Nov", "Dec"
];
var day = date.getDate();
var monthIndex = date.getMonth();
var month = monthNames[monthIndex];
var year = date.getFullYear().toString().substring(2,3);
var hours = date.getHours();
var minutes = date.getMinutes();
return month+' '+day+" '"+year+' at '+hours+':'+minutes;
}
Try this:
var date = new Date();
var formattedDate =
(date.toLocaleString("en-us", { month: "long" })) + " " +
date.getDate() + " '" + (date.getFullYear() % 100);
var formattedTime = date.getHours() + ':' + date.getMinutes();
alert( formattedDate + " at " + formattedTime );
Here's a JSFiddle.

Alternative to toLocaleString() for chrome browser

function tolocal(str)
{
var date, split, dSplit, tSplit, d, raw;
date = '';
split = str.split(' ');
if (split.length === 2) {
dSplit = split[0].split('-');
tSplit = split[1].split(':');
}
raw = d.toLocaleString().split(' GMT')[0];
return raw.substring(raw.indexOf(", ")+2, raw.lastIndexOf(':')) + " " + raw.substring(raw.length-2,raw.length)
}
The above code, works well in ie browser where I get the output in the following format.
November 13,2012 10:15 AM
But I am not able to achieve the same in the chrome browser. Is there any other function which will help me achieve the same output? date.toUTCString() provides the same result but I am not sure how different it is to toLocaleString() in terms of functionality.
Thanks in advance.
Just do it manually:
// Where "date" is a Date object
function dateFormatUTC(date) {
var months = [
'January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'
];
var hours = date.getUTCHours();
if (hours < 10) hours = '0' + hours;
var minutes = date.getUTCMinutes();
if (hours < 10) hours = '0' + hours;
var monthName = months[date.getUTCMonth()];
var timeOfDay = hours < 12 ? 'AM' : 'PM';
return monthName + ' ' + date.getUTCDate() + ', ' +
date.getUTCFullYear() + ' ' + hours + ':' + minutes + timeOfDay;
}
maybe you can use a thirdparty library to do stuff like that: moment.js is a good one.
Example:
moment(d).format('MMMM Do, YYYY h:mms a');
you can try using options like below:
var date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
// request a weekday along with a long date
var options = {weekday: "long", year: "numeric", month: "long", day: "numeric"};
// an application may want to use UTC and make that visible
options.timeZone = "UTC";
options.timeZoneName = "short";
alert(date.toLocaleString("en-US", options));
Please find the reference #
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString

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

Categories

Resources