Related
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);
I need DD-MM-YYYY Format of the given date.
var todaydate = /Date(1394908200000)/; //Serialize date
var date = eval("new " + todaydate.replace(/\//g, ""));
alert('date is :'+date)
but output look like,
date is :Wed Jun 11 2014 00:00:00 GMT+0530 (India Standard Time)
Expected output like,
date is :11-06-2014
Try this
var date = new Date(); //new Date(1394908200000)
function convert(str) {
var date = new Date(str),
mnth = ("0" + (date.getMonth() + 1)).slice(-2),
day = ("0" + date.getDate()).slice(-2);
return [day, mnth, date.getFullYear()].join("-");
}
var final = convert(date);
alert('date is :' + final)
DEMO
Besides of JS like other people mention, you can also use the .datepicker from jquery ui plug-in
var dt = $.datepicker.formatDate('dd-mm-yy', new Date(1394908200000));
alert(dt);
JSFiddle, use jquery ui plug-in
WORKING FIDDLE
Try this-
var date = new Date();
function myDateFormatter (dateobject) {
var d = new Date(dateobject);
var day = d.getDate();
var month = d.getMonth() + 1;
var year = d.getFullYear();
if (day < 10) {
day = "0" + day;
}
if (month < 10) {
month = "0" + month;
}
var date = day + "-" + month + "-" + year;
return date;
};
var dateformat = myDateFormatter(date);
alert('date is :' + dateformat);
I want to know how to use the Date() function in jQuery to get the current date in a yyyy/mm/dd format.
Date() is not part of jQuery, it is one of JavaScript's features.
See the documentation on Date object.
You can do it like that:
var d = new Date();
var month = d.getMonth()+1;
var day = d.getDate();
var output = d.getFullYear() + '/' +
(month<10 ? '0' : '') + month + '/' +
(day<10 ? '0' : '') + day;
See this jsfiddle for a proof.
The code may look like a complex one, because it must deal with months & days being represented by numbers less than 10 (meaning the strings will have one char instead of two). See this jsfiddle for comparison.
If you have jQuery UI (needed for the datepicker), this would do the trick:
$.datepicker.formatDate('yy/mm/dd', new Date());
jQuery is JavaScript. Use the Javascript Date Object.
var d = new Date();
var strDate = d.getFullYear() + "/" + (d.getMonth()+1) + "/" + d.getDate();
Using pure Javascript your can prototype your own YYYYMMDD format;
Date.prototype.yyyymmdd = function() {
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
var dd = this.getDate().toString();
return yyyy + "/" + (mm[1]?mm:"0"+mm[0]) + "/" + (dd[1]?dd:"0"+dd[0]); // padding
};
var date = new Date();
console.log( date.yyyymmdd() ); // Assuming you have an open console
In JavaScript you can get the current date and time using the Date object;
var now = new Date();
This will get the local client machine time
Example for jquery LINK
If you are using jQuery DatePicker you can apply it on any textfield like this:
$( "#datepicker" ).datepicker({dateFormat:"yy/mm/dd"}).datepicker("setDate",new Date());
function GetTodayDate() {
var tdate = new Date();
var dd = tdate.getDate(); //yields day
var MM = tdate.getMonth(); //yields month
var yyyy = tdate.getFullYear(); //yields year
var currentDate= dd + "-" +( MM+1) + "-" + yyyy;
return currentDate;
}
Very handy function to use it, Enjoy. You do not require any javascript framework. it just works in with plain javascript.
I know I am Late But This Is All You Need
var date = (new Date()).toISOString().split('T')[0];
toISOString() use built function of javascript.
cd = (new Date()).toISOString().split('T')[0];
console.log(cd);
alert(cd);
Since the question is tagged as jQuery:
If you are also using jQuery UI you can use $.datepicker.formatDate():
$.datepicker.formatDate('yy/mm/dd', new Date());
See this demo.
Here is method top get current Day, Year or Month
new Date().getDate() // Get the day as a number (1-31)
new Date().getDay() // Get the weekday as a number (0-6)
new Date().getFullYear() // Get the four digit year (yyyy)
new Date().getHours() // Get the hour (0-23)
new Date().getMilliseconds() // Get the milliseconds (0-999)
new Date().getMinutes() // Get the minutes (0-59)
new Date().getMonth() // Get the month (0-11)
new Date().getSeconds() // Get the seconds (0-59)
new Date().getTime() // Get the time (milliseconds since January 1, 1970)
See this.
The $.now() method is a shorthand for the number returned by the expression (new Date).getTime().
Moment.js makes it quite easy:
moment().format("YYYY/MM/DD")
this object set zero, when element has only one symbol:
function addZero(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
This object set actual full time, hour and date:
function getActualFullDate() {
var d = new Date();
var day = addZero(d.getDate());
var month = addZero(d.getMonth()+1);
var year = addZero(d.getFullYear());
var h = addZero(d.getHours());
var m = addZero(d.getMinutes());
var s = addZero(d.getSeconds());
return day + ". " + month + ". " + year + " (" + h + ":" + m + ")";
}
function getActualHour() {
var d = new Date();
var h = addZero(d.getHours());
var m = addZero(d.getMinutes());
var s = addZero(d.getSeconds());
return h + ":" + m + ":" + s;
}
function getActualDate() {
var d = new Date();
var day = addZero(d.getDate());
var month = addZero(d.getMonth()+1);
var year = addZero(d.getFullYear());
return day + ". " + month + ". " + year;
}
HTML:
<span id='full'>a</span>
<br>
<span id='hour'>b</span>
<br>
<span id='date'>c</span>
JQUERY VIEW:
$(document).ready(function(){
$("#full").html(getActualFullDate());
$("#hour").html(getActualHour());
$("#date").html(getActualDate());
});
EXAMPLE
//convert month to 2 digits<p>
var twoDigitMonth = ((fullDate.getMonth().length+1) === 1)? (fullDate.getMonth()+1) : '0' + (fullDate.getMonth()+1);
var currentDate = fullDate.getFullYear()+ "/" + twoDigitMonth + "/" + fullDate.getDate();
console.log(currentDate);<br>
//2011/05/19
You can achieve this with moment.js as well.
Include moment.js in your html.
<script src="moment.js"></script>
And use below code in script file to get formatted date.
moment(new Date(),"YYYY-MM-DD").utcOffset(0, true).format();
FYI - getDay() will give you the day of the week... ie: if today is Thursday, it will return the number 4 (being the 4th day of the week).
To get a proper day of the month, use getDate().
My example below... (also a string padding function to give a leading 0 on single time elements. (eg: 10:4:34 => 10:04:35)
function strpad00(s)
{
s = s + '';
if (s.length === 1) s = '0'+s;
return s;
}
var currentdate = new Date();
var datetime = currentdate.getDate()
+ "/" + strpad00((currentdate.getMonth()+1))
+ "/" + currentdate.getFullYear()
+ " # "
+ currentdate.getHours() + ":"
+ strpad00(currentdate.getMinutes()) + ":"
+ strpad00(currentdate.getSeconds());
Example output: 31/12/2013 # 10:07:49If using getDay(), the output would be 4/12/2013 # 10:07:49
This will give you current date string
var today = new Date().toISOString().split('T')[0];
Try this....
var d = new Date();
alert(d.getFullYear()+'/'+(d.getMonth()+1)+'/'+d.getDate());
getMonth() return month 0 to 11 so we would like to add 1 for accurate month
Reference by : https://www.w3schools.com/jsref/jsref_obj_date.asp
you can use this code:
var nowDate = new Date();
var nowDay = ((nowDate.getDate().toString().length) == 1) ? '0'+(nowDate.getDate()) : (nowDate.getDate());
var nowMonth = ((nowDate.getMonth().toString().length) == 1) ? '0'+(nowDate.getMonth()+1) : (nowDate.getMonth()+1);
var nowYear = nowDate.getFullYear();
var formatDate = nowDay + "." + nowMonth + "." + nowYear;
you can find a working demo here
var d = new Date();
var today = d.getFullYear() + '/' + ('0'+(d.getMonth()+1)).slice(-2) + '/' + ('0'+d.getDate()).slice(-2);
The jQuery plugin page is down. So manually:
function strpad00(s)
{
s = s + '';
if (s.length === 1) s = '0'+s;
return s;
}
var now = new Date();
var currentDate = now.getFullYear()+ "/" + strpad00(now.getMonth()+1) + "/" + strpad00(now.getDate());
console.log(currentDate );
console.log($.datepicker.formatDate('yy/mm/dd', new Date()));
Using the jQuery-ui datepicker, it has a handy date conversion routine built in so you can format dates:
var my_date_string = $.datepicker.formatDate( "yy-mm-dd", new Date() );
Simple.
This is what I came up with using only jQuery. It's just a matter of putting the pieces together.
//Gather date information from local system
var ThisMonth = new Date().getMonth() + 1;
var ThisDay = new Date().getDate();
var ThisYear = new Date().getFullYear();
var ThisDate = ThisMonth.toString() + "/" + ThisDay.toString() + "/" + ThisYear.toString();
//Gather time information from local system
var ThisHour = new Date().getHours();
var ThisMinute = new Date().getMinutes();
var ThisTime = ThisHour.toString() + ":" + ThisMinute.toString();
//Concatenate date and time for date-time stamp
var ThisDateTime = ThisDate + " " + ThisTime;
You can do this:
var now = new Date();
dateFormat(now, "dddd, mmmm dS, yyyy, h:MM:ss TT");
// Saturday, June 9th, 2007, 5:46:21 PM
OR Something like
var dateObj = new Date();
var month = dateObj.getUTCMonth();
var day = dateObj.getUTCDate();
var year = dateObj.getUTCFullYear();
var newdate = month + "/" + day + "/" + year;
alert(newdate);
var d = new Date();
var month = d.getMonth() + 1;
var day = d.getDate();
var year = d.getYear();
var today = (day<10?'0':'')+ day + '/' +(month<10?'0':'')+ month + '/' + year;
alert(today);
I just wanted to share a timestamp prototype I made using Pierre's idea. Not enough points to comment :(
// US common date timestamp
Date.prototype.timestamp = function() {
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
var dd = this.getDate().toString();
var h = this.getHours().toString();
var m = this.getMinutes().toString();
var s = this.getSeconds().toString();
return (mm[1]?mm:"0"+mm[0]) + "/" + (dd[1]?dd:"0"+dd[0]) + "/" + yyyy + " - " + ((h > 12) ? h-12 : h) + ":" + m + ":" + s;
};
d = new Date();
var timestamp = d.timestamp();
// 10/12/2013 - 2:04:19
Get current Date format dd/mm/yyyy
Here is the code:
var fullDate = new Date();
var twoDigitMonth = ((fullDate.getMonth().toString().length) == 1)? '0'+(fullDate.getMonth()+1) : (fullDate.getMonth()+1);
var twoDigitDate = ((fullDate.getDate().toString().length) == 1)? '0'+(fullDate.getDate()) : (fullDate.getDate());
var currentDate = twoDigitDate + "/" + twoDigitMonth + "/" + fullDate.getFullYear();
alert(currentDate);
function createDate() {
var date = new Date(),
yr = date.getFullYear(),
month = date.getMonth()+1,
day = date.getDate(),
todayDate = yr + '-' + month + '-' + day;
console.log("Today date is :" + todayDate);
You can add an extension method to javascript.
Date.prototype.today = function () {
return ((this.getDate() < 10) ? "0" : "") + this.getDate() + "/" + (((this.getMonth() + 1) < 10) ? "0" : "") + (this.getMonth() + 1) + "/" + this.getFullYear();
}
This one-liner will give you YYYY-MM-DD:
new Date().toISOString().substr(0, 10)
'2022-06-09'
When we call getMonth() and getDate() on date object, we will get the single digit number.
For example :
For january, it displays 1, but I need to display it as 01. How to do that?
("0" + this.getDate()).slice(-2)
for the date, and similar:
("0" + (this.getMonth() + 1)).slice(-2)
for the month.
If you want a format like "YYYY-MM-DDTHH:mm:ss", then this might be quicker:
var date = new Date().toISOString().substr(0, 19);
// toISOString() will give you YYYY-MM-DDTHH:mm:ss.sssZ
Or the commonly used MySQL datetime format "YYYY-MM-DD HH:mm:ss":
var date2 = new Date().toISOString().substr(0, 19).replace('T', ' ');
Why not use padStart ?
padStart(targetLength, padString) where
targetLength is 2
padString is 0
// Source: https://stackoverflow.com/a/50769505/2965993
var dt = new Date();
year = dt.getFullYear();
month = (dt.getMonth() + 1).toString().padStart(2, "0");
day = dt.getDate().toString().padStart(2, "0");
console.log(year + '/' + month + '/' + day);
This will always return 2 digit numbers even if the month or day is less than 10.
Notes:
This will only work with Internet Explorer if the js code is transpiled using babel.
getFullYear() returns the 4 digit year and doesn't require padStart.
getMonth() returns the month from 0 to 11.
1 is added to the month before padding to keep it 1 to 12.
getDate() returns the day from 1 to 31.
The 7th day will return 07 and so we do not need to add 1 before padding the string.
Example for month:
function getMonth(date) {
var month = date.getMonth() + 1;
return month < 10 ? '0' + month : '' + month; // ('' + month) for string result
}
You can also extend Date object with such function:
Date.prototype.getMonthFormatted = function() {
var month = this.getMonth() + 1;
return month < 10 ? '0' + month : '' + month; // ('' + month) for string result
}
The best way to do this is to create your own simple formatter (as below):
getDate() returns the day of the month (from 1-31)
getMonth() returns the month (from 0-11) < zero-based, 0=January, 11=December
getFullYear() returns the year (four digits) < don't use getYear()
function formatDateToString(date){
// 01, 02, 03, ... 29, 30, 31
var dd = (date.getDate() < 10 ? '0' : '') + date.getDate();
// 01, 02, 03, ... 10, 11, 12
var MM = ((date.getMonth() + 1) < 10 ? '0' : '') + (date.getMonth() + 1);
// 1970, 1971, ... 2015, 2016, ...
var yyyy = date.getFullYear();
// create the format you want
return (dd + "-" + MM + "-" + yyyy);
}
I would do this:
var date = new Date(2000, 0, 9);
var str = new Intl.DateTimeFormat('en-US', {
month: '2-digit',
day: '2-digit',
year: 'numeric'
}).format(date);
console.log(str); // prints "01/09/2000"
The following is used to convert db2 date format
i.e YYYY-MM-DD using ternary operator
var currentDate = new Date();
var twoDigitMonth=((currentDate.getMonth()+1)>=10)? (currentDate.getMonth()+1) : '0' + (currentDate.getMonth()+1);
var twoDigitDate=((currentDate.getDate())>=10)? (currentDate.getDate()) : '0' + (currentDate.getDate());
var createdDateTo = currentDate.getFullYear() + "-" + twoDigitMonth + "-" + twoDigitDate;
alert(createdDateTo);
Just another example, almost one liner.
var date = new Date();
console.log( (date.getMonth() < 9 ? '0': '') + (date.getMonth()+1) );
function monthFormated(date) {
//If date is not passed, get current date
if(!date)
date = new Date();
month = date.getMonth();
// if month 2 digits (9+1 = 10) don't add 0 in front
return month < 9 ? "0" + (month+1) : month+1;
}
If it might spare some time I was looking to get:
YYYYMMDD
for today, and got along with:
const dateDocumentID = new Date()
.toISOString()
.substr(0, 10)
.replace(/-/g, '');
function monthFormated() {
var date = new Date(),
month = date.getMonth();
return month+1 < 10 ? ("0" + month) : month;
}
This was my solution:
function leadingZero(value) {
if (value < 10) {
return "0" + value.toString();
}
return value.toString();
}
var targetDate = new Date();
targetDate.setDate(targetDate.getDate());
var dd = targetDate.getDate();
var mm = targetDate.getMonth() + 1;
var yyyy = targetDate.getFullYear();
var dateCurrent = leadingZero(mm) + "/" + leadingZero(dd) + "/" + yyyy;
Using Moment.js it can be done like that:
moment(new Date(2017, 1, 1)).format('DD') // day
moment(new Date(2017, 1, 1)).format('MM') // month
const today = new Date().toISOString()
const fullDate = today.split('T')[0];
console.log(fullDate) //prints YYYY-MM-DD
Not an answer but here is how I get the date format I require in a variable
function setDateZero(date){
return date < 10 ? '0' + date : date;
}
var curr_date = ev.date.getDate();
var curr_month = ev.date.getMonth() + 1;
var curr_year = ev.date.getFullYear();
var thisDate = curr_year+"-"+setDateZero(curr_month)+"-"+setDateZero(curr_date);
Hope this helps!
Ternary Operator Solution
A simple ternary operator can add a "0" before the number if the month or day is less than 10 (assuming you need this information for use in a string).
let month = (date.getMonth() < 10) ? "0" + date.getMonth().toString() : date.getMonth();
let day = (date.getDate() < 10) ? "0" + date.getDate().toString() : date.getDate();
The more modern approach perhaps, using "padStart"
const now = new Date();
const day = `${now.getDate()}`.padStart(2, '0');
const month = `${now.getMonth()}`.padStart(2, '0');
const year = now.getFullYear();
then you can build as a template string if you wish:
`${day}/${month}/${year}`
Tip from MDN :
function date_locale(thisDate, locale) {
if (locale == undefined)
locale = 'fr-FR';
// set your default country above (yes, I'm french !)
// then the default format is "dd/mm/YYY"
if (thisDate == undefined) {
var d = new Date();
} else {
var d = new Date(thisDate);
}
return d.toLocaleDateString(locale);
}
var thisDate = date_locale();
var dayN = thisDate.slice(0, 2);
var monthN = thisDate.slice(3, 5);
console.log(dayN);
console.log(monthN);
http://jsfiddle.net/v4qcf5x6/
new Date().getMonth() method returns the month as a number (0-11)
You can get easily correct month number with this function.
function monthFormatted() {
var date = new Date(),
month = date.getMonth();
return month+1 < 10 ? ("0" + month) : month;
}
I would suggest you use a different library called Moment https://momentjs.com/
This way you are able to format the date directly without having to do extra work
const date = moment().format('YYYY-MM-DD')
// date: '2020-01-04'
Make sure you import moment as well to be able to use it.
yarn add moment
# to add the dependency
import moment from 'moment'
// import this at the top of the file you want to use it in
Hope this helps :D
How it easy?
new Date().toLocaleString("en-US", { day: "2-digit" })
Another options are available such:
weekday
year
month
More info here.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString#using_options
function GetDateAndTime(dt) {
var arr = new Array(dt.getDate(), dt.getMonth(), dt.getFullYear(),dt.getHours(),dt.getMinutes(),dt.getSeconds());
for(var i=0;i<arr.length;i++) {
if(arr[i].toString().length == 1) arr[i] = "0" + arr[i];
}
return arr[0] + "." + arr[1] + "." + arr[2] + " " + arr[3] + ":" + arr[4] + ":" + arr[5];
}
And another version here https://jsfiddle.net/ivos/zcLxo8oy/1/, hope to be useful.
var dt = new Date(2016,5,1); // just for the test
var separator = '.';
var strDate = (dt.getFullYear() + separator + (dt.getMonth() + 1) + separator + dt.getDate());
// end of setup
strDate = strDate.replace(/(\b\d{1}\b)/g, "0$1")
The answers here were helpful, however I need more than that: not only month, date, month, hours & seconds, for a default name.
Interestingly, though prepend of "0" was needed for all above, " + 1" was needed only for month, not others.
As example:
("0" + (d.getMonth() + 1)).slice(-2) // Note: +1 is needed
("0" + (d.getHours())).slice(-2) // Note: +1 is not needed
My solution:
function addLeadingChars(string, nrOfChars, leadingChar) {
string = string + '';
return Array(Math.max(0, (nrOfChars || 2) - string.length + 1)).join(leadingChar || '0') + string;
}
Usage:
var
date = new Date(),
month = addLeadingChars(date.getMonth() + 1),
day = addLeadingChars(date.getDate());
jsfiddle: http://jsfiddle.net/8xy4Q/1/
var net = require('net')
function zeroFill(i) {
return (i < 10 ? '0' : '') + i
}
function now () {
var d = new Date()
return d.getFullYear() + '-'
+ zeroFill(d.getMonth() + 1) + '-'
+ zeroFill(d.getDate()) + ' '
+ zeroFill(d.getHours()) + ':'
+ zeroFill(d.getMinutes())
}
var server = net.createServer(function (socket) {
socket.end(now() + '\n')
})
server.listen(Number(process.argv[2]))
if u want getDate() function to return the date as 01 instead of 1, here is the code for it....
Lets assume Today's date is 01-11-2018
var today = new Date();
today = today.getFullYear()+ "-" + (today.getMonth() + 1) + "-" + today.getDate();
console.log(today); //Output: 2018-11-1
today = today.getFullYear()+ "-" + (today.getMonth() + 1) + "-" + ((today.getDate() < 10 ? '0' : '') + today.getDate());
console.log(today); //Output: 2018-11-01
I wanted to do something like this and this is what i did
p.s. i know there are right answer(s) on top, but just wanted to add something of my own here
const todayIs = async () =>{
const now = new Date();
var today = now.getFullYear()+'-';
if(now.getMonth() < 10)
today += '0'+now.getMonth()+'-';
else
today += now.getMonth()+'-';
if(now.getDay() < 10)
today += '0'+now.getDay();
else
today += now.getDay();
return today;
}
If you'll check smaller than 10, you haven't to create a new function for that. Just assign a variable into brackets and return it with ternary operator.
(m = new Date().getMonth() + 1) < 10 ? `0${m}` : `${m}`
currentDate(){
var today = new Date();
var dateTime = today.getFullYear()+'-'+
((today.getMonth()+1)<10?("0"+(today.getMonth()+1)):(today.getMonth()+1))+'-'+
(today.getDate()<10?("0"+today.getDate()):today.getDate())+'T'+
(today.getHours()<10?("0"+today.getHours()):today.getHours())+ ":" +
(today.getMinutes()<10?("0"+today.getMinutes()):today.getMinutes())+ ":" +
(today.getSeconds()<10?("0"+today.getSeconds()):today.getSeconds());
return dateTime;
},
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);