106

Well I have a strange problem while convert from unix timestamp to human representation using javascript

Here is 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 results to be 2011 2, 25 22 00 00. But it is 2011, 2, 6, 0, 0, 0 What I miss ?

georgevich
  • 2,285
  • 6
  • 24
  • 20

7 Answers7

116

getDay() returns the day of the week. To get the date, use date.getDate(). getMonth() retrieves the month, but month is zero based, so using getMonth() + 1 should give you the right month. Time value seems to be ok here, albeit the hour is 23 here (GMT+1). If you want universal values, add UTC to the methods (e.g. date.getUTCFullYear(), date.getUTCHours())

const timestamp = 1301090400;
const date = new Date(timestamp * 1000);
const datevalues = [
   date.getFullYear(),
   date.getMonth()+1,
   date.getDate(),
   date.getHours(),
   date.getMinutes(),
   date.getSeconds(),
];
alert(datevalues); //=> [2011, 3, 25, 23, 0, 0]

Here is a small helper idea to retrieve values of a given Date:

const dateHelper = dateHelperFactory();
const formatMe = date => {
  const vals = [...`yyyy,mm,dd,hh,mmi,ss,mms`.split(`,`)];
  const myDate = dateHelper(date).toArr(...vals);
  return `${myDate.slice(0, 3).join(`/`)} ${
    myDate.slice(3, 6).join(`:`)}.${
    myDate.slice(-1)[0]}`;
};

// to a formatted date with zero padded values
console.log(formatMe(new Date(1301090400 * 1000)));

// the raw values
console.log(dateHelper(new Date(1301090400 * 1000)).values);

function dateHelperFactory() {
  const padZero = (val, len = 2) => `${val}`.padStart(len, `0`);
  const setValues = date => {
    let vals = {
       yyyy: date.getFullYear(),
       m: date.getMonth()+1,
       d: date.getDate(),
       h: date.getHours(),
       mi: date.getMinutes(),
       s: date.getSeconds(),
       ms: date.getMilliseconds(), };
    Object.keys(vals).filter(k => k !== `yyyy`).forEach(k => 
      vals[k[0]+k] = padZero(vals[k], k === `ms` && 3 || 2) );
    return vals;
  };
  
  return date => ( {
    values: setValues(date),
    toArr(...items) { return items.map(i => this.values[i]); },
  } );
}
.as-console-wrapper {
    max-height: 100% !important;
}
KooiInc
  • 112,400
  • 31
  • 139
  • 174
63
var newDate = new Date();
newDate.setTime(unixtime*1000);
dateString = newDate.toUTCString();

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

For example, using it for the current time:

document.write( new Date().toUTCString() );
Joshua Pinter
  • 41,803
  • 23
  • 230
  • 232
Shouvik
  • 10,950
  • 16
  • 54
  • 86
  • I found this answer, and the accepted anwer here [ *.toString() ] to be useful: http://stackoverflow.com/questions/13622142/javascript-to-convert-utc-to-local-time Here is a gist: https://gist.github.com/victoriastuart/b9fb09b890ef88755538b24b0207fece – Victoria Stuart Mar 08 '17 at 23:29
  • 1
    `"unixtime is undefined"` is what I am getting here – Katie Jul 18 '17 at 17:31
  • 1
    Anyway, it can be easily turned in oneliner `new Date(1480966325 * 1000).toUTCString()` – Rozkalns Jul 26 '17 at 13:41
10

here is kooilnc's 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;
}
golakers
  • 123
  • 1
  • 7
9

use Date.prototype.toLocaleTimeString() as documented here

please note the locale example en-US in the url.

Regolith
  • 2,867
  • 9
  • 31
  • 47
struggle4life
  • 91
  • 1
  • 1
7

Hours, minutes and seconds depend on the time zone of your operating system. In GMT (UST) it's 22:00:00 but in different timezones it can be anything. So add the timezone offset to the time to create the GMT date:

var d = new Date();
date = new Date(timestamp*1000 + d.getTimezoneOffset() * 60000)
Hossein
  • 3,959
  • 2
  • 22
  • 45
5

I was looking for a very specific solution for returning the current time as a guaranteed length string to prepend at the beginning of every log line. Here they are if someone else is looking for the same thing.

Basic Timestamp

"2021-05-26 06:46:33"

The following function returns a zero padded timestamp for the current time (always 19 characters long)

function getTimestamp () {
  const pad = (n,s=2) => (`${new Array(s).fill(0)}${n}`).slice(-s);
  const d = new Date();
  
  return `${pad(d.getFullYear(),4)}-${pad(d.getMonth()+1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
}

Full Timestamp

"2021-06-02 07:08:19.041"

The following function returns a zero padded timestamp for the current time including milliseconds (always 23 characters long)

function getFullTimestamp () {
  const pad = (n,s=2) => (`${new Array(s).fill(0)}${n}`).slice(-s);
  const d = new Date();
  
  return `${pad(d.getFullYear(),4)}-${pad(d.getMonth()+1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}.${pad(d.getMilliseconds(),3)}`;
}
DaveAlger
  • 2,196
  • 24
  • 23
0

To direct get a readable local timezone:

var timestamp = 1301090400,
date = new Date(timestamp * 1000)
document.write( date.toLocaleString() );
harrrrrrry
  • 11,303
  • 1
  • 19
  • 27