Convert a timestamp to YYYY-MM-DD with JS [duplicate] - javascript

I am storing time in a MySQL database as a Unix timestamp and that gets sent to some JavaScript code. How would I get just the time out of it?
For example, in HH/MM/SS format.

let unix_timestamp = 1549312452
// Create a new JavaScript Date object based on the timestamp
// multiplied by 1000 so that the argument is in milliseconds, not seconds.
var date = new Date(unix_timestamp * 1000);
// Hours part from the timestamp
var hours = date.getHours();
// Minutes part from the timestamp
var minutes = "0" + date.getMinutes();
// Seconds part from the timestamp
var seconds = "0" + date.getSeconds();
// Will display time in 10:30:23 format
var formattedTime = hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
console.log(formattedTime);
For more information regarding the Date object, please refer to MDN or the ECMAScript 5 specification.

function timeConverter(UNIX_timestamp){
var a = new Date(UNIX_timestamp * 1000);
var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
var year = a.getFullYear();
var month = months[a.getMonth()];
var date = a.getDate();
var hour = a.getHours();
var min = a.getMinutes();
var sec = a.getSeconds();
var time = date + ' ' + month + ' ' + year + ' ' + hour + ':' + min + ':' + sec ;
return time;
}
console.log(timeConverter(0));

JavaScript works in milliseconds, so you'll first have to convert the UNIX timestamp from seconds to milliseconds.
var date = new Date(UNIX_Timestamp * 1000);
// Manipulate JavaScript Date object here...

Use:
var s = new Date(1504095567183).toLocaleDateString("en-US")
console.log(s)
// expected output "8/30/2017"
and for time:
var s = new Date(1504095567183).toLocaleTimeString("en-US")
console.log(s)
// expected output "3:19:27 PM"
see Date.prototype.toLocaleDateString()

Modern Solution (for 2020)
In the new world, we should be moving towards the standard Intl JavaScript object, that has a handy DateTimeFormat constructor with .format() method:
function format_time(s) {
const dtFormat = new Intl.DateTimeFormat('en-GB', {
timeStyle: 'medium',
timeZone: 'UTC'
});
return dtFormat.format(new Date(s * 1e3));
}
console.log( format_time(12345) ); // "03:25:45"
Eternal Solution
But to be 100% compatible with all legacy JavaScript engines, here is the shortest one-liner solution to format seconds as hh:mm:ss:
function format_time(s) {
return new Date(s * 1e3).toISOString().slice(-13, -5);
}
console.log( format_time(12345) ); // "03:25:45"
Method Date.prototype.toISOString() returns time in
simplified extended ISO 8601 format, which is always 24 or 27 characters long (i.e. YYYY-MM-DDTHH:mm:ss.sssZ or
±YYYYYY-MM-DDTHH:mm:ss.sssZ respectively). The timezone is always
zero UTC offset.
This solution does not require any third-party libraries and is supported in all browsers and JavaScript engines.

I'm partial to Jacob Wright's Date.format() library, which implements JavaScript date formatting in the style of PHP's date() function.
new Date(unix_timestamp * 1000).format('h:i:s')

I'd think about using a library like momentjs.com, that makes this really simple:
Based on a Unix timestamp:
var timestamp = moment.unix(1293683278);
console.log( timestamp.format("HH/mm/ss") );
Based on a MySQL date string:
var now = moment("2010-10-10 12:03:15");
console.log( now.format("HH/mm/ss") );

shortest one-liner solution to format seconds as hh:mm:ss: variant:
console.log(new Date(1549312452 * 1000).toISOString().slice(0, 19).replace('T', ' '));
// "2019-02-04 20:34:12"

In moment you must use unix timestamp:
const dateTimeString = moment.unix(1466760005).format("DD-MM-YYYY HH:mm:ss");

This works with PHP timestamps
var d = 1541415288860;
//var d =val.timestamp;
//NB: use + before variable name
var date = new Date(+d);
console.log(d);
console.log(date.toDateString());
console.log(date.getFullYear());
console.log(date.getMinutes());
console.log(date.getSeconds());
console.log(date.getHours());
console.log(date.toLocaleTimeString());
var d =val.timestamp;
var date=new Date(+d); //NB: use + before variable name
console.log(d);
console.log(date.toDateString());
console.log(date.getFullYear());
console.log(date.getMinutes());
console.log(date.getSeconds());
console.log(date.getHours());
console.log(date.toLocaleTimeString());
the methods above will generate this results
1541415288860
Mon Nov 05 2018
2018
54
48
13
1:54:48 PM
There's a bunch of methods that work perfectly with timestamps. Cant list them all

UNIX timestamp is number of seconds since 00:00:00 UTC on January 1, 1970 (according to Wikipedia).
Argument of Date object in Javascript is number of miliseconds since 00:00:00 UTC on January 1, 1970 (according to W3Schools Javascript documentation).
See code below for example:
function tm(unix_tm) {
var dt = new Date(unix_tm*1000);
document.writeln(dt.getHours() + '/' + dt.getMinutes() + '/' + dt.getSeconds() + ' -- ' + dt + '<br>');
}
tm(60);
tm(86400);
gives:
1/1/0 -- Thu Jan 01 1970 01:01:00 GMT+0100 (Central European Standard Time)
1/0/0 -- Fri Jan 02 1970 01:00:00 GMT+0100 (Central European Standard Time)

Using Moment.js, you can get time and date like this:
var dateTimeString = moment(1439198499).format("DD-MM-YYYY HH:mm:ss");
And you can get only time using this:
var timeString = moment(1439198499).format("HH:mm:ss");

The problem with the aforementioned solutions is, that if hour, minute or second, has only one digit (i.e. 0-9), the time would be wrong, e.g. it could be 2:3:9, but it should rather be 02:03:09.
According to this page it seems to be a better solution to use Date's "toLocaleTimeString" method.

Another way - from an ISO 8601 date.
var timestamp = 1293683278;
var date = new Date(timestamp * 1000);
var iso = date.toISOString().match(/(\d{2}:\d{2}:\d{2})/)
alert(iso[1]);

Based on #shomrat's answer, here is a snippet that automatically writes datetime like this (a bit similar to StackOverflow's date for answers: answered Nov 6 '16 at 11:51):
today, 11:23
or
yersterday, 11:23
or (if different but same year than today)
6 Nov, 11:23
or (if another year than today)
6 Nov 2016, 11:23
function timeConverter(t) {
var a = new Date(t * 1000);
var today = new Date();
var yesterday = new Date(Date.now() - 86400000);
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
var year = a.getFullYear();
var month = months[a.getMonth()];
var date = a.getDate();
var hour = a.getHours();
var min = a.getMinutes();
if (a.setHours(0,0,0,0) == today.setHours(0,0,0,0))
return 'today, ' + hour + ':' + min;
else if (a.setHours(0,0,0,0) == yesterday.setHours(0,0,0,0))
return 'yesterday, ' + hour + ':' + min;
else if (year == today.getFullYear())
return date + ' ' + month + ', ' + hour + ':' + min;
else
return date + ' ' + month + ' ' + year + ', ' + hour + ':' + min;
}

function getTIMESTAMP() {
var date = new Date();
var year = date.getFullYear();
var month = ("0" + (date.getMonth() + 1)).substr(-2);
var day = ("0" + date.getDate()).substr(-2);
var hour = ("0" + date.getHours()).substr(-2);
var minutes = ("0" + date.getMinutes()).substr(-2);
var seconds = ("0" + date.getSeconds()).substr(-2);
return year + "-" + month + "-" + day + " " + hour + ":" + minutes + ":" + seconds;
}
//2016-01-14 02:40:01

The modern solution that doesn't need a 40 KB library:
Intl.DateTimeFormat is the non-culturally imperialistic way to format a date/time.
// Setup once
var options = {
//weekday: 'long',
//month: 'short',
//year: 'numeric',
//day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric'
},
intlDate = new Intl.DateTimeFormat( undefined, options );
// Reusable formatter
var timeStamp = 1412743273;
console.log( intlDate.format( new Date( 1000 * timeStamp ) ) );

Pay attention to the zero problem with some of the answers. For example, the timestamp 1439329773 would be mistakenly converted to 12/08/2015 0:49.
I would suggest on using the following to overcome this issue:
var timestamp = 1439329773; // replace your timestamp
var date = new Date(timestamp * 1000);
var formattedDate = ('0' + date.getDate()).slice(-2) + '/' + ('0' + (date.getMonth() + 1)).slice(-2) + '/' + date.getFullYear() + ' ' + ('0' + date.getHours()).slice(-2) + ':' + ('0' + date.getMinutes()).slice(-2);
console.log(formattedDate);
Now results in:
12/08/2015 00:49

There are multiple ways to convert unix timestamp to time (HH/MM/SS)
Using new Date() - this is in-built in javascript
moment package - this is a famous node module, but this is going to deprecate.
dayjs package - this is one of the latest and fast growing node module
Using new Date()
const dateTimeStr = new Date(1504052527183).toLocaleString()
const result = (dateTimeStr.split(", ")[1]).split(":").join("/")
console.log(result)
Using moment
const moment = require('moment')
const timestampObj = moment.unix(1504052527183);
const result = timestampObj.format("HH/mm/ss")
console.log(result);
Using day.js
const dayjs = require('dayjs')
const result = dayjs(1504052527183).format("HH/mm/ss")
console.log(result);
you can check the timestamp to time conversion with an online time conversion tool

// Format value as two digits 0 => 00, 1 => 01
function twoDigits(value) {
if(value < 10) {
return '0' + value;
}
return value;
}
var date = new Date(unix_timestamp*1000);
// display in format HH:MM:SS
var formattedTime = twoDigits(date.getHours())
+ ':' + twoDigits(date.getMinutes())
+ ':' + twoDigits(date.getSeconds());

function getDateTimeFromTimestamp(unixTimeStamp) {
let date = new Date(unixTimeStamp);
return ('0' + date.getDate()).slice(-2) + '/' + ('0' + (date.getMonth() + 1)).slice(-2) + '/' + date.getFullYear() + ' ' + ('0' + date.getHours()).slice(-2) + ':' + ('0' + date.getMinutes()).slice(-2);
}
const myTime = getDateTimeFromTimestamp(1435986900000);
console.log(myTime); // output 01/05/2000 11:00

You can use the following function to convert your timestamp to HH:MM:SS format :
var convertTime = function(timestamp, separator) {
var pad = function(input) {return input < 10 ? "0" + input : input;};
var date = timestamp ? new Date(timestamp * 1000) : new Date();
return [
pad(date.getHours()),
pad(date.getMinutes()),
pad(date.getSeconds())
].join(typeof separator !== 'undefined' ? separator : ':' );
}
Without passing a separator, it uses : as the (default) separator :
time = convertTime(1061351153); // --> OUTPUT = 05:45:53
If you want to use / as a separator, just pass it as the second parameter:
time = convertTime(920535115, '/'); // --> OUTPUT = 09/11/55
Demo
var convertTime = function(timestamp, separator) {
var pad = function(input) {return input < 10 ? "0" + input : input;};
var date = timestamp ? new Date(timestamp * 1000) : new Date();
return [
pad(date.getHours()),
pad(date.getMinutes()),
pad(date.getSeconds())
].join(typeof separator !== 'undefined' ? separator : ':' );
}
document.body.innerHTML = '<pre>' + JSON.stringify({
920535115 : convertTime(920535115, '/'),
1061351153 : convertTime(1061351153, ':'),
1435651350 : convertTime(1435651350, '-'),
1487938926 : convertTime(1487938926),
1555135551 : convertTime(1555135551, '.')
}, null, '\t') + '</pre>';
See also this Fiddle.

function timeConverter(UNIX_timestamp){
var a = new Date(UNIX_timestamp*1000);
var hour = a.getUTCHours();
var min = a.getUTCMinutes();
var sec = a.getUTCSeconds();
var time = hour+':'+min+':'+sec ;
return time;
}

See Date/Epoch Converter.
You need to ParseInt, otherwise it wouldn't work:
if (!window.a)
window.a = new Date();
var mEpoch = parseInt(UNIX_timestamp);
if (mEpoch < 10000000000)
mEpoch *= 1000;
------
a.setTime(mEpoch);
var year = a.getFullYear();
...
return time;

Shortest
(new Date(ts*1000)+'').slice(16,24)
let ts = 1549312452;
let time = (new Date(ts*1000)+'').slice(16,24);
console.log(time);

Try this :
new Date(1638525320* 1e3).toISOString() //2021-12-03T09:55:20.000Z

function getDateTime(unixTimeStamp) {
var d = new Date(unixTimeStamp);
var h = (d.getHours().toString().length == 1) ? ('0' + d.getHours()) : d.getHours();
var m = (d.getMinutes().toString().length == 1) ? ('0' + d.getMinutes()) : d.getMinutes();
var s = (d.getSeconds().toString().length == 1) ? ('0' + d.getSeconds()) : d.getSeconds();
var time = h + '/' + m + '/' + s;
return time;
}
var myTime = getDateTime(1435986900000);
console.log(myTime); // output 01/15/00

moment.js
convert timestamps to date string in js
https://momentjs.com/
moment().format('YYYY-MM-DD hh:mm:ss');
// "2020-01-10 11:55:43"
moment(1578478211000).format('YYYY-MM-DD hh:mm:ss');
// "2020-01-08 06:10:11"

If you want to convert Unix time duration to real hours, minutes, and seconds, you could use the following code:
var hours = Math.floor(timestamp / 60 / 60);
var minutes = Math.floor((timestamp - hours * 60 * 60) / 60);
var seconds = Math.floor(timestamp - hours * 60 * 60 - minutes * 60 );
var duration = hours + ':' + minutes + ':' + seconds;

Code below also provides 3-digit millisecs, ideal for console log prefixes:
const timeStrGet = date => {
const milliSecsStr = date.getMilliseconds().toString().padStart(3, '0') ;
return `${date.toLocaleTimeString('it-US')}.${milliSecsStr}`;
};
setInterval(() => console.log(timeStrGet(new Date())), 299);

Related

Javascript format date

I have a date string which coming from the db as follows
/Date(1469167371657)/
Is there any way to convert this date to following format using javascript
MM/DD/YYYY HH:MM
I've searched a lot but unble to find a solution
In plain javascript you have to write your own function for string format a date, for example for your string format:
var date = new Date(1469167371657);
function stringDate(date) {
var mm = date.getMonth()+1;
mm = (mm<10?"0"+mm:mm);
var dd = date.getDate();
dd = (dd<10?"0"+dd:dd);
var hh = date.getHours();
hh = (hh<10?"0"+hh:hh);
var min = date.getMinutes();
min = (min<10?"0"+min:min);
return mm+'/'+dd+'/'+date.getFullYear()+" "+hh+":"+min;
}
console.log(stringDate(date));
drier code version
var date = new Date(1469167371657);
function stringDate(date) {
return ("0" + (date.getMonth() + 1)).slice(-2)+'/'
+("0" + date.getDate()).slice(-2)+'/'
+date.getFullYear()+" "
+("0" + date.getHours()).slice(-2)+':'
+("0" + date.getMinutes()).slice(-2)
}
console.log(stringDate(date));
with pure js you can do the folowing
var d = new Date();
console.log(d.getMonth() + 1 + "/" + d.getDate() + "/" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes())
You can use - http://momentjs.com/ and have it done like:
moment(1469167371657).format('MM/DD/YYYY HH:MM')
You can do this with the following steps:
1) convert the timestamp to a date object.
var timestamp = "/Date(1469167371657)/"; // However you want to save whatever comes from your database
timestamp = timestamp.substr(timestamp.indexOf("(")+1); // gives 1469167371657)/
timestamp = timestamp.substr(0,timestamp.indexOf(")")); // gives 1469167371657
var d = new Date(timestamp);
2) set it to your format
function leadZero(i) {if(i < 10) {return "0"+i;} return i;} // Simple function to convert 5 to 05 e.g.
var time = leadZero(d.getMonth()+1)+"/"+leadZero(d.getDate())+"/"+d.getFullYear()+" "+leadZero(d.getHours())+":"+leadZero(d.getMinutes());
alert(time);
Note: the date / timestamp you provided is too high for javascript to understand, so this example will not work correclty
I believe that number is milliseconds so to convert it to date, you would do this:
var time = new Date().getTime();
var date = new Date(time);
alert(date.toString()); // Wed Jan 12 2011 12:42:46 GMT-0800 (PST)
var time=1469167371657;
var date = new Date(time);
alert(date.toString());

JavaScript DateTime not working

function formatDate(dt) {
//var date = new Date(dt);
var date = new Date('2015-08-27 16:00:00'); alert(date.getMonth());
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;
var strTime = hours + ':' + minutes + ':' + seconds + ' ' + ampm;
return date.getDate() + " " + date.getMonth() + " " + date.getFullYear() + " " + strTime;
}
I have tried to fetch Date and time. But I am getting NaN while alert date.getMonth();.
If I am removing time then this is working fine. But My date-time format dynamic. This is coming from the database like 0000-00-00 00:00:00.
I want to view my database date and time in the 27 Aug 2015 04:00:00 am/pm format.
The date format you are using (2015-08-27 16:00:00) is not the proper format for Firefox, though it works in Chrome. So, for this code to work properly on all browsers, it should not be used.
The below code works in Firefox and Chrome:
I've replaced the string variable date - with /. This format works for both Firefox and Chrome.
Another format that works in Firefox and Chrome is 1995-12-17T03:24:00 which includes T instead of ' ' (space).
However, the above format gives different value in Chrome and Firefox.
new Date('2015-10-05T03:24:00'); // Returns Mon Oct 05 2015 08:54:00 GMT+0530 (IST) in Chrome
new Date('2015-10-05T03:24:00'); // Returns 2015-10-04T21:54:00.000Z in Firefox
var date1 = '2015-08-20 09:38:20';
var date1Updated = new Date(date1.replace(/-/g,'/'));
alert(date1Updated.getMonth());
var strDate = addZero(d.getDate()) + "/" + addZero((d.getMonth() + 1))+"/" +d.getFullYear();
alert("strDate :"+strDate)
return strDate;
}
function addZero(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
The getMonth() method returns the month (from 0 to 11) for the specified date, according to local time.
Note: January is 0, February is 1, and so on.
you need to add one like getMonth() + 1.
function formatDate(dt) {
//var date = new Date(dt);
var date = new Date('2015-08-27 16:00:00');
//alert(date.getMonth() + 1);
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;
var strTime = hours + ':' + minutes + ':' + seconds + ' ' + ampm;
return date.getDate() + " " + (date.getMonth() + 1) + " " + date.getFullYear() + " " + strTime;
}
alert(formatDate());
In firefox '2015-08-27 16:00:00' is an invalid date.
Your options are
var today = new Date();
var birthday = new Date('December 17, 1995 03:24:00');
var birthday = new Date('1995-12-17T03:24:00');
var birthday = new Date(1995, 11, 17);
var birthday = new Date(1995, 11, 17, 3, 24, 0);
In your case you're missing the T before the time
Documentation
You have an invalid date format, It seems Chrome handle this situation but firefox not.
new Date('2015-08-27 16:00:00') // Invalid format
new Date('2015-08-27T16:00:00') // Correct Format With T
Your code doesn't work in firefox
In firefox 2015-08-27 16:00:00isn't valid.
To be valid it has to be 2015-08-27T16:00:00.
To make it valid in firefox, the easiest solution would be
function formatDate(dt) {
//var date = new Date(dt);
var sampleDate = "2015-08-27 16:00:00"; // Your sample date as string
var another = sampleDate.replace(' ', 'T');// Change here. Replaced the empty space with the 'T' to make it work in firefox
var date = new Date(another); alert(date.getMonth()); // Using your date to create new Date object
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;
var strTime = hours + ':' + minutes + ':' + seconds + ' ' + ampm;
return date.getDate() + " " + date.getMonth() + " " + date.getFullYear() + " " + strTime;
}
Hope i was helpfull
Parsing strings using the Date constructor is largely implementation dependent. Only one format of string is specified as being supported by the specification and that changed to some extent between ES5 and ECMAScript 2015.
Your best option is to manually parse the string, either using your own function or a library. The following will suit if the string is consistently the format in the OP and the timezone is UTC:
/* parse dates of format yyyy-mm-dd hh:mm:ss
** e.g. 2015-08-27 16:00:00
**
** #param {string} s - Date string in format yyyy-mm-dd hh:mm:ss
** #returns {Date} - String as Date assuming UTC
**
** Does not validate that the string is valid date or time
**/
function parseDate (s) {
var b = s.split(/\D/);
return new Date(Date.UTC(b[0], b[1]-1, b[2], b[3], b[4], b[5]));
}
document.write(parseDate('2015-08-27 16:00:00'));

How to get time from date object without time zone in javascript?

I have Date object like
Date {Mon Aug 17 2015 05:45:23 GMT+0530 (IST)}
i want only time without GMT timezone and IST.I want only time like 05:45:23.thanks
You can use moment javascript library to format and process your dates.
The alternative option is manually accessing date hours, minutes and seconds.
Check the Date Reference.
You can build a string by using:
var formattedDate = date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
Using pure JavaScript:
var d = new Date(),
hours = d.getHours(),
mins = d.getMinutes(),
secs = d.getSeconds(),
time = hours + ':' + mins + ':' + secs;
console.log(time);
You can create your own prototype extending the Date object.
Date.prototype.extractTime = function(){
var h = this.getHours();
var m = this.getMinutes();
var s = this.getSeconds();
return h + ":" + m + ":" + s;
}
Usage:
var d = new Date();
d.extractTime(); // outputs current time of your clock..

Combine date and time string into single date with javascript

I have a datepicker returning a date string, and a timepicker returning just a time string.
How should I combine those into a single javascript Date?
I thought I found a solution in Date.js. The examples shows an at( )-method, but I can't find it in the library...
You can configure your date picker to return format like YYYY-mm-dd (or any format that Date.parse supports) and you could build a string in timepicker like:
var dateStringFromDP = '2013-05-16';
$('#timepicker').timepicker().on('changeTime.timepicker', function(e) {
var timeString = e.time.hour + ':' + e.time.minute + ':00';
var dateObj = new Date(datestringFromDP + ' ' + timeString);
});
javascript Date object takes a string as the constructor param
Combine date and time to string like this:
1997-07-16T19:20:15
Then you can parse it like this:
Date.parse('1997-07-16T19:20:15');
You could also use moment.js or something similar.
For plain JavaScript:
combineDateAndTime = function(date, time) {
timeString = time.getHours() + ':' + time.getMinutes() + ':00';
var year = date.getFullYear();
var month = date.getMonth() + 1; // Jan is 0, dec is 11
var day = date.getDate();
var dateString = '' + year + '-' + month + '-' + day;
var combined = new Date(dateString + ' ' + timeString);
return combined;
};
You can concatenate the date and time, and then use moment to get the datetime
const date = '2018-12-24';
const time = '23:59:59';
const dateTime = moment(`${date} ${time}`, 'YYYY-MM-DD HH:mm:ss').format();
Boateng's example fails in cases where time consisted of hours, minutes, days or months that ranged from values 0-9 as getDate(), getMonth() etc... will return 1 digit in these cases and the time string will fail and an invalid date is returned:
function CombineDateAndTime(date, time) {
const mins = ("0"+ time.getMinutes()).slice(-2);
const hours = ("0"+ time.getHours()).slice(-2);
const timeString = hours + ":" + mins + ":00";
const year = date.getFullYear();
const month = ("0" + (date.getMonth() + 1)).slice(-2);
const day = ("0" + date.getDate()).slice(-2);
const dateString = "" + year + "-" + month + "-" + day;
const datec = dateString + "T" + timeString;
return new Date(datec);
};
Unfortunately do not have enough rep to comment
David's example with slight modifications:
function CombineDateAndTime(date, time) {
var timeString = time.getHours() + ':' + time.getMinutes() + ':00';
var ampm = time.getHours() >= 12 ? 'PM' : 'AM';
var year = date.getFullYear();
var month = date.getMonth() + 1; // Jan is 0, dec is 11
var day = date.getDate();
var dateString = '' + year + '-' + month + '-' + day;
var datec = dateString + 'T' + timeString;
var combined = new Date(datec);
return combined;
};
Concate date and time with moment JS which also works on firefox,
let d1 = moment().format('MM/DD/YYYY');
let dateTimeOpen = moment(d1 + ' ' + model.openingTime).format('YYYY-MM-DD HH:mm:ss');
let dateTimeClose = moment(d1 + ' ' + model.closingTime).format('YYYY-MM-DD HH:mm:ss');
const date = "2022-12-27";
const time = "16:26:42";
new Date(`${date}T${time});
output
Date Tue Dec 27 2022 16:26:42 GMT+0100 (Central European Standard Time)

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