How do I get the current time only in JavaScript - javascript

How can I get the current time in JavaScript and use it in a timepicker?
I tried var x = Date() and got:
Tue May 15 2012 05:45:40 GMT-0500
But I need only current time, for example, 05:45
How can I assign this to a variable?

var d = new Date("2011-04-20T09:30:51.01");
d.getHours(); // => 9
d.getMinutes(); // => 30
d.getSeconds(); // => 51
or
var d = new Date(); // for now
d.getHours(); // => 9
d.getMinutes(); // => 30
d.getSeconds(); // => 51

Short and simple:
new Date().toLocaleTimeString(); // 11:18:48 AM
//---
new Date().toLocaleDateString(); // 11/16/2015
//---
new Date().toLocaleString(); // 11/16/2015, 11:18:48 PM
4 hours later (use milisec: sec==1000):
new Date(new Date().getTime() + 4*60*60*1000).toLocaleTimeString(); // 3:18:48 PM or 15:18:48
2 days before:
new Date(new Date().getTime() - 2*24*60*60*1000).toLocaleDateString() // 11/14/2015

Get and set the current time efficiently using javascript
I couldn't find a solution that did exactly what I needed. I wanted clean and tiny code so I came up with this:
PURE JAVASCRIPT
function timeNow(i) {
var d = new Date(),
h = (d.getHours()<10?'0':'') + d.getHours(),
m = (d.getMinutes()<10?'0':'') + d.getMinutes();
i.value = h + ':' + m;
}
<a onclick="timeNow(test1)" href="#">SET TIME</a>
<input id="test1" type="time" value="10:40" />
UPDATE
There is now sufficient browser support to simply use: toLocaleTimeString
For html5 type time the format must be hh:mm.
function timeNow(i) {
i.value = new Date().toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
}
<a onclick="timeNow(test1)" href="#">SET TIME</a>
<input id="test1" type="time" value="10:40" />
Try it on jsfiddle

You can simply use this methods.
console.log(new Date().toLocaleTimeString([], { hour: '2-digit', minute: "2-digit", hour12: false }));
console.log(new Date().toLocaleTimeString([], { hour: '2-digit', minute: "2-digit" }));

Try
new Date().toLocaleTimeString().replace("/.*(\d{2}:\d{2}:\d{2}).*/", "$1");
Or
new Date().toTimeString().split(" ")[0];

const date = Date().slice(16,21);
console.log(date);

Do you mean:
var d = new Date();
var curr_hour = d.getHours();
var curr_min = d.getMinutes();

Try this:
var date = new Date();
var hour = date.getHours();
var min = date.getMinutes();

function getCurrentTime(){
var date = new Date();
var hh = date.getHours();
var mm = date.getMinutes();
hh = hh < 10 ? '0'+hh : hh;
mm = mm < 10 ? '0'+mm : mm;
curr_time = hh+':'+mm;
return curr_time;
}

This how you can do it.
const date = new Date();
const time = date.toTimeString().split(' ')[0].split(':');
console.log(time[0] + ':' + time[1])

See these Date methods ...
toLocaleTimeString - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleTimeString
toTimeString - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toTimeString

Try this
new Date().toTimeString().slice(0, 8);
or
new Date().toTimeString().split(" ")[0];
It should work.

this -
var x = new Date();
var h = x.getHours();
var m = x.getMinutes();
var s = x.getSeconds();
so-
x = date
h = hours
m = mins
s = seconds

A simple way to do this in ES6, in the format you requested (hh:mm), would be this way:
const goodTime = `${new Date().getHours()}:${new Date().getMinutes()}`;
console.log(goodTime);
(Obviously, the console logging is not part of the solution)

This is the shortest way.
var now = new Date().toLocaleTimeString();
console.log(now)
Here is also a way through string manipulation that was not mentioned.
var now = new Date()
console.log(now.toString().substr(16,8))

var today = new Date(); //gets current date and time
var hour = today.getHours();
var minute = today.getMinutes();
var second = today.getSeconds();

Simple functions to get Date and Time separated and with compatible format with Time and Date HTML input
function formatDate(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
return [year, month, day].join('-');
}
function formatTime(date) {
var hours = new Date().getHours() > 9 ? new Date().getHours() : '0' + new Date().getHours()
var minutes = new Date().getMinutes() > 9 ? new Date().getMinutes() : '0' + new Date().getMinutes()
return hours + ':' + minutes
}

getTime() {
let today = new Date();
let h = today.getHours();
let m = today.getMinutes();
let s = today.getSeconds();
h = h < 10 ? "0" + h : h;
m = m < 10 ? "0" + m : m;
s = s < 10 ? "0" + s : s;
let time = h + ":" + m + ":" + s;
return time;
},

Assign to variables and display it.
time = new Date();
var hh = time.getHours();
var mm = time.getMinutes();
var ss = time.getSeconds()
document.getElementById("time").value = hh + ":" + mm + ":" + ss;

This worked for me but this depends on what you get when you hit Date():
Date().slice(16,-12)

Here is how I'm doing this: (Hope it helps someone)
What I'm doing is validating the time that the user enters in the HTML time input is not in the past:
let inputTime = value; // from time input in html (06:29)
const splittedInputTime = inputTime.split(':');
let currentDate = new Date();
currentDate.setHours(splittedInputTime[0]);
currentDate.setMinutes(splittedInputTime[1]);
const finalInputTime = currentDate.toTimeString().split(" ")[0];
const currentTime = new Date().toTimeString().split(" ")[0];
// Returns a boolean (true/ false)
let validTime = finalInputTime >= currentTime;

Date.toLocaleTimeString() options
The Date.toLocaleTimeString() function can receive an options parameter to format the output
Some of the available options are these
new Date().toLocaleTimeString([], { timeStyle: "full" }) // 4:43:58 AM Pacific Standard Time
new Date().toLocaleTimeString([], { timeStyle: "long" }) // 4:43:58 AM PST
new Date().toLocaleTimeString([], { timeStyle: "medium" }) // 4:43:58 AM
new Date().toLocaleTimeString([], { timeStyle: "short" }) // 4:43 AM
Or you can specify the representation of the hour, minute, and second with these values:
"numeric" (e.g., 1)
"2-digit" (e.g., 01)
new Date().toLocaleTimeString([], { hour: '2-digit', minute: "2-digit" })
// 04:43 AM
Or set the 12-hour time using hour12: true or false
For more details take a look at
Date.toLocaleTimeString() parameters and
Intl.DateTimeFormat() options

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;
var strTime = hours + ':' + minutes + ' ' + ampm;
console.log(strTime);
$scope.time = strTime;
date.setDate(date.getDate()+1);
month = '' + (date.getMonth() + 1),
day = '' + date.getDate(1),
year = date.getFullYear();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
var tomorrow = [year, month, day].join('-');
$scope.tomorrow = tomorrow;

Related

JavaScript, wrong yyyy-mm-dd of today

I need to get the yyyy-mm-dd of today on const today2. I'm trying this:
const today = new Date();
console.log('today', today)
// today Wed Mar 11 2020 23:13:35 GMT-0300 (hora de verano de Chile)
const today2 = new Date().toISOString().slice(0,10);
console.log('today2', today2)
// today2 2020-03-12
I need to get 2020-03-11 but I'm getting 2020-03-12
why? I don't want to use moment
Try this:
const today = new Date();
const today2 = new Date(today.getTime() - (today.getTimezoneOffset() * 60000)).toISOString().slice(0,10);
Using toISOString() converts the timezone to UTC(standard time)
Try this function..
export const getTodayDate = () => {
var today = new Date();
var dd = (today.getDate()).toString();
var mm = (today.getMonth() + 1).toString();
var yyyy = (today.getFullYear()).toString();
if (parseInt(dd) < 10) {
dd = '0' + dd;
}
if (parseInt(mm) < 10) {
mm = '0' + mm;
}
return yyyy + '-' + mm + '-' + dd;
}
const today2 = getTodayDate();
console.log(today2);
I got it from: https://stackoverflow.com/a/50130338/3541320
const today = new Date();
const todayYYYMMDD = new Date(today.getTime() - (today.getTimezoneOffset() * 60000 ))
.toISOString()
.split("T")[0];

Invalid Date Ionic 3 in IOS

Invalid Date Error in ionic 3 in IOS only. (Working fine in Android).
var f = data.posted_date +' '+ data.posted_time;
var d = new Date(); // working Fine
var b = new Date(f); // b becomes invalid Date
its working fine in android but not working in IOS.
Complete Function:
getProperTime() {
this.dailyDiary.forEach(element => {
var d = new Date(element.posted_date + " " + element.posted_time);
var hours: any = d.getHours();
var minutes: any = d.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 = hours + ":" + minutes + " " + ampm;
console.log("this is the getProperTime function output: " + strTime);
element.posted_time = strTime;
});
}
This function shows as result:
12:NaN am
It looks like Date Format Issue in Safari View.
var d = new Date("2011-02-07");
Above Mentioned Format is Not supported in Internet Explorer and Safari.
these two browsers surprisingly do not support the date format “yyyy-mm-dd” and therefore fail. Supported across all browsers and would advise sticking to one of these to avoid errors:
var d = new Date(2011, 01, 07); // yyyy, mm-1, dd
var d = new Date(2011, 01, 07, 11, 05, 00); // yyyy, mm-1, dd, hh, mm, ss
var d = new Date("02/07/2011"); // "mm/dd/yyyy"
var d = new Date("02/07/2011 11:05:00"); // "mm/dd/yyyy hh:mm:ss"
var d = new Date(1297076700000); // milliseconds
var d = new Date("Mon Feb 07 2011 11:05:00 GMT"); // ""Day Mon dd yyyy hh:mm:ss GMT/UTC

Trying to get rid of some letters in string

let myDate = new Date();
myDate.toLocaleString;
So if I'll console log the value of myDate will be:
Wed Oct 16 2019 15:57:22 GMT+0300 (Israel Daylight Time)
What if I want the value to be only 57:22? (Minutes and seconds of the hour).
How do I do that?
Have a go with this
const getMMSS = (str) => str.match(/:\d{2}:\d{2}/)[0].slice(1);
// tests
const myDate = new Date(2019,09,16,23,59,59,999);
let dateStr = myDate.toLocaleString();
console.log(getMMSS(dateStr))
dateStr = "Wed Oct 16 2019 15:57:22 GMT+0300 (Israel Daylight Time)"
console.log(getMMSS(dateStr))
Or just
const pad = (num) => ("0"+num).slice(-2);
const myDate = new Date();
console.log(`${pad(myDate.getMinutes())}:${pad(myDate.getSeconds())}`)
You can use Date's own methods to do this:
let date = new Date();
let m = date.getMinutes();
let s = date.getSeconds();
console.log(m + ':' + s);
To make the final result more readable you can check if the minutes and seconds are smaller than 10 and, if so, append a 0 to the beginning:
let date = new Date();
let m = date.getMinutes();
let s = date.getSeconds();
m = m < 10 ? ('0' + m) : m;
s = s < 10 ? ('0' + s) : s;
console.log(m + ':' + s);
You may use basic javascript Date methods:
var myDate = new Date();
var formatted =`${myDate.getMinutes()}:${myDate.getSeconds()}`;
console.log(formatted);
OR using moment.js library
var myDate = new Date();
var formatted = moment(myDate).format("mm:ss");
console.log(formatted);
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.min.js"></script>

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;

Getting current date and time in JavaScript

I have a script that prints the current date and time in JavaScript, but the DATE is always wrong. Here is the code:
var currentdate = new Date();
var datetime = "Last Sync: " + currentdate.getDay() + "/" + currentdate.getMonth()
+ "/" + currentdate.getFullYear() + " # "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":" + currentdate.getSeconds();
It should print 18/04/2012 15:07:33 and prints 3/3/2012 15:07:33
.getMonth() returns a zero-based number so to get the correct month you need to add 1, so calling .getMonth() in may will return 4 and not 5.
So in your code we can use currentdate.getMonth()+1 to output the correct value. In addition:
.getDate() returns the day of the month <- this is the one you want
.getDay() is a separate method of the Date object which will return an integer representing the current day of the week (0-6) 0 == Sunday etc
so your code should look like this:
var currentdate = new Date();
var datetime = "Last Sync: " + currentdate.getDate() + "/"
+ (currentdate.getMonth()+1) + "/"
+ currentdate.getFullYear() + " # "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":"
+ currentdate.getSeconds();
JavaScript Date instances inherit from Date.prototype. You can modify the constructor's prototype object to affect properties and methods inherited by JavaScript Date instances
You can make use of the Date prototype object to create a new method which will return today's date and time. These new methods or properties will be inherited by all instances of the Date object thus making it especially useful if you need to re-use this functionality.
// For todays date;
Date.prototype.today = function () {
return ((this.getDate() < 10)?"0":"") + this.getDate() +"/"+(((this.getMonth()+1) < 10)?"0":"") + (this.getMonth()+1) +"/"+ this.getFullYear();
}
// For the time now
Date.prototype.timeNow = function () {
return ((this.getHours() < 10)?"0":"") + this.getHours() +":"+ ((this.getMinutes() < 10)?"0":"") + this.getMinutes() +":"+ ((this.getSeconds() < 10)?"0":"") + this.getSeconds();
}
You can then simply retrieve the date and time by doing the following:
var newDate = new Date();
var datetime = "LastSync: " + newDate.today() + " # " + newDate.timeNow();
Or call the method inline so it would simply be -
var datetime = "LastSync: " + new Date().today() + " # " + new Date().timeNow();
To get time and date you should use
new Date().toLocaleString();
>> "09/08/2014, 2:35:56 AM"
To get only the date you should use
new Date().toLocaleDateString();
>> "09/08/2014"
To get only the time you should use
new Date().toLocaleTimeString();
>> "2:35:56 AM"
Or if you just want the time in the format hh:mm without AM/PM for US English
new Date().toLocaleTimeString('en-US', { hour12: false,
hour: "numeric",
minute: "numeric"});
>> "02:35"
or for British English
new Date().toLocaleTimeString('en-GB', { hour: "numeric",
minute: "numeric"});
>> "02:35"
Read more here.
For true mysql style output use this function below: 2019/02/28 15:33:12
If you click the 'Run code snippet' button below
It will show you 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>
Just use:
var d = new Date();
document.write(d.toLocaleString());
document.write("<br>");
Short
I develop Steve answer to get exactly what OP need
new Date().toLocaleString().replace(',','')
console.log(new Date().toLocaleString().replace(',',''));
var currentdate = new Date();
var datetime = "Last Sync: " + currentdate.getDate() + "/"+(currentdate.getMonth()+1)
+ "/" + currentdate.getFullYear() + " # "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":" + currentdate.getSeconds();
Change .getDay() method to .GetDate() and add one to month, because it counts months from 0.
This should do the trick:
function dateToString(date) {
var month = date.getMonth() + 1;
var day = date.getDate();
var dateOfString = (("" + day).length < 2 ? "0" : "") + day + "/";
dateOfString += (("" + month).length < 2 ? "0" : "") + month + "/";
dateOfString += date.getFullYear();
return dateOfString;
}
var currentdate = new Date();
var datetime = "Last Sync: ";
datetime += dateToString(currentdate );
datetime += + currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":"
+ currentdate.getSeconds();
Basic JS (good to learn): we use the Date() function and do all that we need to show the date and day in our custom format.
var myDate = new Date();
let daysList = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
let monthsList = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Aug', 'Oct', 'Nov', 'Dec'];
let date = myDate.getDate();
let month = monthsList[myDate.getMonth()];
let year = myDate.getFullYear();
let day = daysList[myDate.getDay()];
let today = `${date} ${month} ${year}, ${day}`;
let amOrPm;
let twelveHours = function (){
if(myDate.getHours() > 12)
{
amOrPm = 'PM';
let twentyFourHourTime = myDate.getHours();
let conversion = twentyFourHourTime - 12;
return `${conversion}`
}else {
amOrPm = 'AM';
return `${myDate.getHours()}`}
};
let hours = twelveHours();
let minutes = myDate.getMinutes();
let currentTime = `${hours}:${minutes} ${amOrPm}`;
console.log(today + ' ' + currentTime);
Node JS (quick & easy): Install the npm pagckage using (npm install date-and-time), then run the below.
let nodeDate = require('date-and-time');
let now = nodeDate.format(new Date(), 'DD-MMMM-YYYY, hh:mm:ss a');
console.log(now);
Short and simple:-
console.log(new Date().toLocaleString());
Reference
I have found the simplest way to get current date and time in JavaScript from here - How to get current Date and Time using JavaScript
var today = new Date();
var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var CurrentDateTime = date+' '+time;
getDay() gets the day of the week. 3 is Wednesday. You want getDate(), that will return 18.
Also getMonth() starts at 0, you need to add 1 to get 4 (April).
DEMO: http://jsfiddle.net/4zVxp/
You need to use getDate() to get the date part. The getDay() function returns the day number (Sunday = 0, Monday = 1...), and the getMonth() returns a 0 based index, so you need to increment it by 1.
var currentdate = new Date();
var datetime = "Last Sync: " + currentdate.getDate() + "/"+ (parseInt(currentdate.getMonth()) + 1)
+ "/" + currentdate.getFullYear() + " # "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":" + currentdate.getSeconds();
const date = new Date()
console.log(date.toLocaleTimeString("en-us", {timeStyle: "medium"})) // Only Time
console.log(date.toLocaleString()) // For both Date and Time
For Documentation
function getTimeStamp() {
var now = new Date();
return ((now.getMonth() + 1) + '/' + (now.getDate()) + '/' + now.getFullYear() + " " + now.getHours() + ':'
+ ((now.getMinutes() < 10) ? ("0" + now.getMinutes()) : (now.getMinutes())) + ':' + ((now.getSeconds() < 10) ? ("0" + now
.getSeconds()) : (now.getSeconds())));
}
get current date and time
var now = new Date();
var datetime = now.getFullYear()+'/'+(now.getMonth()+1)+'/'+now.getDate();
datetime += ' '+now.getHours()+':'+now.getMinutes()+':'+now.getSeconds();
This question is quite old and the answers are too. Instead of those monstrous functions, we now can use moment.js to get the current date, which actually makes it very easy. All that has to be done is including moment.js in our project and get a well formated date, for example, by:
moment().format("dddd, MMMM Do YYYY, h:mm:ss a");
I think that makes it way easier to handle dates in javascript.
.getDay returns day of week. You need .getDate instead.
.getMonth returns values from 0 to 11. You'll need to add 1 to the result to get "human" month number.
This little code is easy and works everywhere.
<p id="dnt"></p>
<script>
document.getElementById("dnt").innerHTML = Date();
</script>
there is room to design
function UniqueDateTime(format='',language='en-US'){
//returns a meaningful unique number based on current time, and milliseconds, making it virtually unique
//e.g : 20170428-115833-547
//allows personal formatting like more usual :YYYYMMDDHHmmSS, or YYYYMMDD_HH:mm:SS
var dt = new Date();
var modele="YYYYMMDD-HHmmSS-mss";
if (format!==''){
modele=format;
}
modele=modele.replace("YYYY",dt.getFullYear());
modele=modele.replace("MM",(dt.getMonth()+1).toLocaleString(language, {minimumIntegerDigits: 2, useGrouping:false}));
modele=modele.replace("DD",dt.getDate().toLocaleString(language, {minimumIntegerDigits: 2, useGrouping:false}));
modele=modele.replace("HH",dt.getHours().toLocaleString(language, {minimumIntegerDigits: 2, useGrouping:false}));
modele=modele.replace("mm",dt.getMinutes().toLocaleString(language, {minimumIntegerDigits: 2, useGrouping:false}));
modele=modele.replace("SS",dt.getSeconds().toLocaleString(language, {minimumIntegerDigits: 2, useGrouping:false}));
modele=modele.replace("mss",dt.getMilliseconds().toLocaleString(language, {minimumIntegerDigits: 3, useGrouping:false}));
return modele;
}
dt= new Date();
alert(dt.toISOString().substring(8,10) + "/" +
dt.toISOString().substring(5,7)+ "/" +
dt.toISOString().substring(0,4) + " " +
dt.toTimeString().substring(0,8))
var datetime = new Date().toLocaleString().slice(0,9) +" "+new Date(new Date()).toString().split(' ')[4];
console.log(datetime);
I think i am very late to share my answer, but i think it will be worth.
function __getCurrentDateTime(format){
var dt=new Date(),x,date=[];
date['d']=dt.getDate();
date['dd']=dt.getDate()>10?dt.getDate():'0'+dt.getDate();
date['m']=dt.getMonth()+1;
date['mm']=(dt.getMonth()+1)>10?(dt.getMonth()+1):'0'+(dt.getMonth()+1);
date['yyyy']=dt.getFullYear();
date['yy']=dt.getFullYear().toString().slice(-2);
date['h']=(dt.getHours()>12?dt.getHours()-12:dt.getHours());
date['hh']=dt.getHours();
date['mi']=dt.getMinutes();
date['mimi']=dt.getMinutes()<10?('0'+dt.getMinutes()):dt.getMinutes();
date['s']=dt.getSeconds();
date['ss']=dt.getSeconds()<10?('0'+dt.getSeconds()):dt.getSeconds();
date['sss']=dt.getMilliseconds();
date['ampm']=(dt.getHours()>=12?'PM':'AM');
x=format.toLowerCase();
x=x.indexOf('dd')!=-1?x.replace(/(dd)/i,date['dd']):x.replace(/(d)/i,date['d']);
x=x.indexOf('mm')!=-1?x.replace(/(mm)/i,date['mm']):x.replace(/(m)/i,date['m']);
x=x.indexOf('yyyy')!=-1?x.replace(/(yyyy)/i,date['yyyy']):x.replace(/(yy)/i,date['yy']);
x=x.indexOf('hh')!=-1?x.replace(/(hh)/i,date['hh']):x.replace(/(h)/i,date['h']);
x=x.indexOf('mimi')!=-1?x.replace(/(mimi)/i,date['mimi']):x.replace(/(mi)/i,date['mi']);
if(x.indexOf('sss')!=-1){ x=x.replace(/(sss)/i,date['sss']); }
x=x.indexOf('ss')!=-1?x.replace(/(ss)/i,date['ss']):x.replace(/(s)/i,date['s']);
if(x.indexOf('ampm')!=-1){ x=x.replace(/(ampm)/i,date['ampm']); }
return x;
}
console.log(__getCurrentDateTime()); //returns in dd-mm-yyyy HH:MM:SS
console.log(__getCurrentDateTime('dd-mm-yyyy')); //return in 05-12-2016
console.log(__getCurrentDateTime('dd/mm*yyyy')); //return in 05/12*2016
console.log(__getCurrentDateTime('hh:mimi:ss')); //return in 13:05:30
console.log(__getCurrentDateTime('h:mi:ss ampm')); //return in 1:5:30 PM
I needed to figure this out for a slate in after effects. Here's what I came up with after taking elements from a few different sources -- Formatting is MM/DD/YYYY HH:MM AM/PM
D = new Date(Date(00));
M = D.getMonth()+1;
H = D.getHours();
Mi = D.getMinutes();
N = "AM"
if (H >= 12)
N = "PM"
if (H > 12)
{
H = H-12
}
amtOfZeroes = 2;
isNeg = false;
if (M < 0)
{
M = Math.abs(M);
isNeg = true;
}
Mo = Math.round(M) + "";
while(Mo.length < amtOfZeroes)
{
Mo = "0" + Mo;
}
if (isNeg)
Mo = "-" + Mo;
if (H < 0)
{
H = Math.abs(H);
isNeg = true;
}
Ho = Math.round(H) + "";
while(Ho.length < amtOfZeroes)
{
Ho = "0" + Ho;
}
if (isNeg)
Ho = "-" + Ho;
if (Mi < 0)
{
Mi = Math.abs(Mi);
isNeg = true;
}
Min = Math.round(Mi) + "";
while(Min.length < amtOfZeroes)
{
Min = "0" + Min;
}
if (isNeg)
Min = "-" + Min;
T = Ho + ":" + (Min)
Mo + "/" + D.getDate() + "/" + D.getFullYear() + " " + T + " " + N
If someone is in search of function
console.log(formatAMPM());
function formatAMPM() {
var date = new Date();
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
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 strTime = date.getMonth() + '/' + date.getDay()+'/'+date.getFullYear()+' '+ hours + ':' + minutes +':'+ seconds + " " +ampm;
}
function display_c(){
var refresh = 1000; // Refresh rate in milli seconds
mytime = setTimeout('display_ct()', refresh)
}
function display_ct() {
var strcount
var currentdate = new Date();
document.getElementById('ct').innerHTML = currentdate.toDateString() + " " + currentdate.getHours() + ":" + currentdate.getMinutes() + ":" + currentdate.getSeconds();
tt = display_c();
}
id = 'ct' // Replace in Your id
onload = "display_ct();" // Type inside a Body Tag
My well intended answer is to use this tiny bit of JS: https://github.com/rhroyston/clock-js
clock.now --> 1462248501241
clock.time --> 11:08 PM
clock.weekday --> monday
clock.day --> 2
clock.month --> may
clock.year --> 2016
clock.since(1462245888784) --> 44 minutes
clock.until(1462255888784) --> 2 hours
clock.what.time(1462245888784) --> 10:24 PM
clock.what.weekday(1461968554458) --> friday
clock.what.day('14622458887 84') --> 2
clock.what.month(1461968554458) --> april
clock.what.year('1461968554458') --> 2016
clock.what.time() --> 11:11 PM
clock.what.weekday('14619685abcd') --> clock.js error : expected unix timestamp as argument
clock.unit.seconds --> 1000
clock.unit.minutes --> 60000
clock.unit.hours --> 3600000
clock.unit.days --> 86400000
clock.unit.weeks --> 604800000
clock.unit.months --> 2628002880
clock.unit.years --> 31536000000
Its simple and superb
$(document).ready(function () {
var fpsOut = document.getElementById('myTime');
setInterval(function () {
var d = new Date();
fpsOut.innerHTML = d;
}, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myTime"></div>
please find the below fiddler for the example
http://jsfiddle.net/4zVxp/483/
Here is my work around clock full format with day, date, year and time
and make Sure the date of your PC is set to the right date and if you are using PHP make sure in php.ini date.timezone= xx where xx your current timezone
function startTime()
{
var today=new Date();
// 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
var suffixes = ['','st','nd','rd','th','th','th','th','th','th','th','th','th','th','th','th','th','th','th','th','th','st','nd','rd','th','th','th','th','th','th','th','st','nd','rd'];
var weekday = new Array(7);
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
var month = new Array(12);
month[0] = "January";
month[1] = "February";
month[2] = "March";
month[3] = "April";
month[4] = "May";
month[5] = "June";
month[6] = "July";
month[7] = "August";
month[8] = "September";
month[9] = "October";
month[10] = "November";
month[11] = "December";
document.getElementById('txt').innerHTML=(weekday[today.getDay()] + ',' + " " + today.getDate()+'<sup>'+suffixes[today.getDate()]+'</sup>' + ' of' + " " + month[today.getMonth()] + " " + today.getFullYear() + ' Time Now ' + today.toLocaleTimeString());
t=setTimeout(function(){startTime()},500);
}
<style>
sup {
vertical-align: super;
font-size: smaller;
}
</style>
<html>
<body onload="startTime()">
<div id="txt"></div>
</body>
</html>
This example of UK Time Zone.. set offset for specific Time Zone.
Example : for India : +05:30 , UK : +1
function realUKTime() {
// create Date object for current location
var d = new Date();
offset ='+1';
// convert to msec
// subtract local time zone offset
// get UTC time in msec
var utc = d.getTime() + (d.getTimezoneOffset() * 60000);
// create new Date object for different city
// using supplied offset
var nd = new Date(utc + (3600000*offset));
// return time as a string
var s = nd.getSeconds();
var i = nd.getMinutes();
var h = nd.getHours();
var cDate = nd.getDate();
var m = nd.getUTCMonth();
var y = nd.getFullYear();
var newUkTime = nd.toDateString() + " "+ (Number(h)-1)+":"+i+':'+s
$("#realTime").html(newUkTime);
}
setInterval(realUKTime(),1000);
Output :: Mon Dec 27 2021 12:6:3
we can use :
new Date().toLocaleDateString() to fetch current date and
new Date().toLocaleTimeString() to fetch current time
Ex:
const date = new Date().toLocaleDateString();
const time = new Date().toLocaleTimeString();

Categories

Resources