Human reading timestamp

Well, I have a weird problem when you convert from unix timestamp to human view using javascript

Here is the timestamp

1301090400 

This is my javascript

 var date = new Date(timestamp * 1000); var year = date.getFullYear(); var month = date.getMonth(); var day = date.getDay(); var hour = date.getHours(); var minute = date.getMinutes(); var seconds = date.getSeconds(); 

I expected the results to be 2011 2, 25 22 00 00. But this is 2011, 2, 6, 0, 0, 0 What did I miss?

+50
javascript timestamp
Mar 24 '11 at 9:12
source share
5 answers

getDay() returns the day of the week. To get the date, use date.getDate() . getMonth() returns a month, but the month is zero, so using getMonth()+1 should give you the correct month. The time value seems to be good here, although the hour is 23 (GMT + 1). If you want universal values, add UTC to the methods (e.g. date.getUTCFullYear() , date.getUTCHours() )

 var timestamp = 1301090400, date = new Date(timestamp * 1000), datevalues = [ date.getFullYear(), date.getMonth()+1, date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds(), ]; alert(datevalues); //=> [2011, 3, 25, 23, 0, 0] 
+72
Mar 24 '11 at 9:17
source share
 var newDate = new Date(); newDate.setTime(unixtime*1000); dateString = newDate.toUTCString(); 

Where unixtime is the time returned by your sql db. Here's a fiddle if that helps.

For example, using it for the current time:

 document.write( new Date().toUTCString() ); 
+19
Mar 24 '11 at 9:40
source share

Hours, minutes, and seconds depend on the time zone of your operating system. In GMT (UST) it is 22:00:00, but in different time zones it can be anything. Therefore, add the time zone offset to the GMT date creation time:

 var d = new Date(); date = new Date(timestamp*1000 + d.getTimezoneOffset() * 60000) 
+7
Mar 24 '11 at 9:32
source share

here kooilnc answer w / padded 0's

 function getFormattedDate() { var date = new Date(); var month = date.getMonth() + 1; var day = date.getDate(); var hour = date.getHours(); var min = date.getMinutes(); var sec = date.getSeconds(); month = (month < 10 ? "0" : "") + month; day = (day < 10 ? "0" : "") + day; hour = (hour < 10 ? "0" : "") + hour; min = (min < 10 ? "0" : "") + min; sec = (sec < 10 ? "0" : "") + sec; var str = date.getFullYear() + "-" + month + "-" + day + "_" + hour + ":" + min + ":" + sec; /*alert(str);*/ return str; } 
+5
Aug 18 '15 at 1:37
source share

use Date.prototype.toLocaleTimeString() as documented here

look at the en-US locale example in the url.

0
Nov 16 '17 at 9:42 on
source share



All Articles