Convert a Unix timestamp to time in JavaScript - 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
Change time stamp from unix to MM/DD/YYY in a multidimensional array [duplicate]
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);
Date day(24 hours) minus date
I need to take away the day from the date that I get, that is 24 hours minus 23:47:16 I have to get 12:44. I tried to break the date variable into a string and take it away, but I just can’t find the algorithm, maybe this can be done with the moment, tell me please 24:00:00 (minus) (const date or const formattedTime) = ... (in my example 24:00:00 - 23:47:16 = 12:44) const date1: any = new Date(Date.now()); const date2: any = new Date(marked_deletion_at); const diffTime = Math.abs(date2 - date1); const date = new Date(diffTime); console.log(date) // Thu Jan 01 1970 23:47:16 GMT+0300 const hours = date.getHours(); const minutes = '0' + date.getMinutes(); const seconds = '0' + date.getSeconds(); // Will display time in 10:30:23 format const formattedTime = hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2); console.log(formattedTime) // 23:47:16
You could do with moment .diff method const datetime = '2020-02-20 23:47:16'; const your_time = moment(datetime); const close_time = moment(datetime).endOf('day') let h = close_time.diff(your_time,'hours') let m = close_time.diff(your_time,'minutes') console.log(h+':'+m) <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
If you simply want to subtract a time in h:mm:ss format from 24:00:00, then convert to some common base (e.g. seconds), subtract, then convert back to h:mm:ss, e.g. // Convert time in h:mm:ss format to seconds function toSecs(time) { let b = time.split(':'); return b[0]*3600 + b[1]*60 + b[2]*1; } // Convert seconds to h:mm:ss format function toTime(secs) { return (secs/3600 | 0) + ':' + ('' + ((secs%3600)/60 |0)).padStart(2, '0') + ':' + ('' + (secs%60)).padStart(2, '0'); } // Time to midnight tonight let z = n => (n<10?'0':'') + n; let now = new Date(); let time = now.getHours() + ':' + z(now.getMinutes()) + ':' + z(now.getSeconds()); console.log('Current time: ' + time); console.log('To midnight : ' + toTime(8.64e4 - toSecs(time))) Note that the functions don't handle negative numbers.
Try this: var date1 = moment("2020-03-19 23:47:16"); var date2 = moment("2020-03-19 24:00:00"); var hours = date2.diff(date1, "hours"); var mins = moment .utc(moment(date2, "HH:mm:ss").diff(moment(date1, "HH:mm:ss"))) .format("mm"); var seconds = moment .utc(moment(date2, "HH:mm:ss").diff(moment(date1, "HH:mm:ss"))) .format("ss"); console.log(hours); console.log(mins); console.log(seconds); <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
How do I get a date in YYYY-MM-DD format?
Normally if I wanted to get the date I could just do something like var d = new Date(); console.log(d); The problem with doing that, is when I run that code, it returns: Mon Aug 24 2015 4:20:00 GMT-0800 (Pacific Standard Time) How could I get the Date() method to return a value in a "MM-DD-YYYY" format so it would return something like: 8/24/2015 Or, maybe MM-DD-YYYY H:M 8/24/2016 4:20
Just use the built-in .toISOString() method like so: toISOString().split('T')[0]. Simple, clean and all in a single line. var date = (new Date()).toISOString().split('T')[0]; document.getElementById('date').innerHTML = date; <div id="date"></div> Please note that the timezone of the formatted string is UTC rather than local time.
The below code is a way of doing it. If you have a date, pass it to the convertDate() function and it will return a string in the YYYY-MM-DD format: var todaysDate = new Date(); function convertDate(date) { var yyyy = date.getFullYear().toString(); var mm = (date.getMonth()+1).toString(); var dd = date.getDate().toString(); var mmChars = mm.split(''); var ddChars = dd.split(''); return yyyy + '-' + (mmChars[1]?mm:"0"+mmChars[0]) + '-' + (ddChars[1]?dd:"0"+ddChars[0]); } console.log(convertDate(todaysDate)); // Returns: 2015-08-25
Yet another way: var today = new Date().getFullYear()+'-'+("0"+(new Date().getMonth()+1)).slice(-2)+'-'+("0"+new Date().getDate()).slice(-2) document.getElementById("today").innerHTML = today <div id="today">
By using Moment.js library, you can do: var datetime = new Date("2015-09-17 15:00:00"); datetime = moment(datetime).format("YYYY-MM-DD");
var today = new Date(); function formatDate(date) { var dd = date.getDate(); var mm = date.getMonth() + 1; //January is 0! var yyyy = date.getFullYear(); if (dd < 10) { dd = '0' + dd; } if (mm < 10) { mm = '0' + mm; } //return dd + '/' + mm + '/' + yyyy; return yyyy + '/' + mm + '/' +dd ; } console.log(formatDate(today));
function formatdate(userDate){ var omar= new Date(userDate); y = omar.getFullYear().toString(); m = omar.getMonth().toString(); d = omar.getDate().toString(); omar=y+m+d; return omar; } console.log(formatDate("12/31/2014"));
What you want to achieve can be accomplished with native JavaScript. The object Date has methods that generate exactly the output you wish. Here are code examples: var d = new Date(); console.log(d); >>> Sun Jan 28 2018 08:28:04 GMT+0000 (GMT) console.log(d.toLocaleDateString()); >>> 1/28/2018 console.log(d.toLocaleString()); >>> 1/28/2018, 8:28:04 AM There is really no need to reinvent the wheel.
If you are trying to get the 'local-ISO' date string. Try the code below. function (date) { return new Date(+date - date.getTimezoneOffset() * 60 * 1000).toISOString().split(/[TZ]/).slice(0, 2).join(' '); } +date Get milliseconds from a date. Ref: Date.prototype.getTimezoneOffset Have fun with it :)
Here is a simple function I created when once I kept working on a project where I constantly needed to get today, yesterday, and tomorrow's date in this format. function returnYYYYMMDD(numFromToday = 0){ let d = new Date(); d.setDate(d.getDate() + numFromToday); const month = d.getMonth() < 9 ? '0' + (d.getMonth() + 1) : d.getMonth() + 1; const day = d.getDate() < 10 ? '0' + d.getDate() : d.getDate(); return `${d.getFullYear()}-${month}-${day}`; } console.log(returnYYYYMMDD(-1)); // returns yesterday console.log(returnYYYYMMDD()); // returns today console.log(returnYYYYMMDD(1)); // returns tomorrow Can easily be modified to pass it a date instead, but here you pass a number and it will return that many days from today.
If you're not opposed to adding a small library, Date-Mirror (NPM or unpkg) allows you to format an existing date in YYYY-MM-DD into whatever date string format you'd like. date('n/j/Y', '2020-02-07') // 2/7/2020 date('n/j/Y g:iA', '2020-02-07 4:45PM') // 2/7/2020 4:45PM date('n/j [until] n/j', '2020-02-07', '2020-02-08') // 2/7 until 2/8 Disclaimer: I developed Date-Mirror.
This will convert a unix timestamp to local date (+ time) function UnixTimeToLocalDate = function( unix_epoch_time ) { var date, str; date = new Date( unix_epoch_time * 1000 ); str = date.getFullYear() + '-' + (date.getMonth() + 1 + '').padStart( 2, '0' ) + '-' + (date.getDate() + '').padStart( 2, '0' ); // If you need hh:mm:ss too then str += ' ' + (date.getHours() + '').padStart( 2, '0' ) + ':' + (date.getMinutes() + '').padStart( 2, '0' ) + ':' + (date.getSeconds() + '').padStart( 2, '0' ); return str; }
If you want a text format that's good for sorting use: function formatDateYYYYMMDDHHMMSS(date){ // YYYY-MM-DD HH:MM:SS const datePart = date.toISOString().split("T")[0] const timePart = date.toLocaleString('en-US', {hour12: false}).split(",")[1] return datePart + timePart } As prototype: Date.prototype.toSortString = function(){ const date = new Date(this.valueOf()); return date.toISOString().split("T")[0] + date.toLocaleString('en-US', {hour12: false}).split(",")[1] }
Simple one line elegant solution for fullYear-fullMonth-FullDay as '2000-01-01' new Date().toLocaleDateString("fr-CA", {year:"numeric", month: "2-digit", day:"2-digit"} )
const padTo2Digits = num => { return num.toString().padStart(2, '0') } const formatDate = date => { return [ date.getFullYear(), padTo2Digits(date.getMonth() + 1), padTo2Digits(date.getDate()) ].join('-') } let value = formatDate(new Date()) document.getElementById('dayFormatUS').innerHTML = value const transformDate = date => { const convert = date.split('-').reverse() return convert.join('/') } document.getElementById('dayFormatBR').innerHTML = transformDate(value) <div> Format US - <span id='dayFormatUS'></span> </div> <div> Format BR - <span id='dayFormatBR'></span> </div>
Convert a string (in date format) to datetime using Javascript
In BIRT, i have a column containing a datetime stored as a string. I need to convert these string to datetime format and put the result in another column using Javascript. The string is the form of: for example: Fri 21 Feb 2014, 09:40 AM. Hence this when converted to a datetime format and exported to excel, the column should be treat as a date. Can any one of you help me to do it? Cheers,
Other answers do not take into consideration this question is in a BIRT context. Create a computed column in your dataset, with "Date time" as datatype Enter as expression: new Date(row["myDateStringField"]); Where "myDateStringField" is your DateTime column in a String format. Then use this computed column in your report instead of the String column. That's it!
Checkout momentjs! You can parse your time of any format like moment("12-25-1995", "MM-DD-YYYY"); In your case, you don't even have to specify the format. It automatically recognizes it. And you can output ISO format or convert it to a Javascript Date object.
This is extremely easy to do with javascript. The following code will make a date in a format that Excel will recognize as a date. http://jsfiddle.net/bbankes/d7SwQ/ var dateString = 'Fri 21 Feb 2014, 09:40 AM'; var date = new Date(dateString); var yr = date.getFullYear(); var mo = date.getMonth() + 1; var day = date.getDate(); var hours = date.getHours(); var hr = hours < 10 ? '0' + hours : hours; var minutes = date.getMinutes(); var min = (minutes < 10) ? '0' + minutes : minutes; var seconds = date.getSeconds(); var sec = (seconds < 10) ? '0' + seconds : seconds; var newDateString = yr + '-' + mo + '-' + day; var newTimeString = hr + ':' + min + ':' + sec; var excelDateString = newDateString + ' ' + newTimeString;
If you just want to reformat 'Fri 21 Feb 2014, 09:04 AM' as '2014-02-21 09:04', then the following will do: function stringToTimestamp(s) { var t = s.match(/[\d\w]+/g); var months = {jan:'01',feb:'02',mar:'03',apr:'04',may:'05',jun:'06', jul:'07',aug:'08',sep:'09',oct:'10',nov:'11',dec:'12'}; function pad(n){return (n<10?'0':'') + +n;} var hrs = t[4] % 12; hrs += /pm$/i.test(t[6])? 12 : 0; return t[3] + '-' + months[t[2].toLowerCase()] + '-' + pad(t[1]) + ' ' + pad(hrs) + ':' + pad(t[5]); } console.log(stringToTimestamp('Fri 21 Feb 2014, 09:04 AM')); // 2014-02-21 09:04
use the ISO format: YYYY-MM-DDTHH:MM:SS or YYYY-MM-DD new Date('2011-04-11T11:51:00'); or new Date('2011-04-11');
convert unix time to date object
I have a unix time and need to get a Date object from it. This code just transform the timestamp to human readable way: var date = new Date(unix_timestamp*1000); var hours = date.getHours(); var minutes = date.getMinutes(); var seconds = date.getSeconds(); var formattedTime = hours + ':' + minutes + ':' + seconds; As a result I get 13:44:6, for instance but how I can create a Date object with time and date from it?
You can take a look at date.js http://www.datejs.com/ var datestr = "13:44:06"; var date = Date.parse(datestr,"hh:mm:ss"); alert(date); This alerts a date string set to today's date, but with the time in datestr. NOTE For this to work, I needed to zero-pad the seconds. EDIT The link for date.js format specifiers is a bit buried, so here's that link if you need it: http://code.google.com/p/datejs/wiki/FormatSpecifiers
I wrote a prototype function for Date object to convert unix timestamp to YYYYMMDD. You can edit it as you like var bd = new Date(unix_timestamp * 1000); bd = bd.toYYYYMMDD(); // 1970-01-01 if ( !Date.prototype.toYYYYMMDD ) { ( function() { function pad(number) { var r = String(number); if ( r.length === 1 ) { r = '0' + r; } return r; } Date.prototype.toYYYYMMDD = function() { if(!this.getUTCDate() || this.getUTCDate() === 'NaN') return '1970-01-01'; return this.getUTCFullYear() + '-' + pad( this.getUTCMonth() + 1 ) + '-' + pad( this.getUTCDate() ); }; }() ); };