113

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,385
  • 7
  • 24
  • 21

8 Answers8

124

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;
}

Or see this small stackblitz project (a little bit more efficient).

KooiInc
  • 119,216
  • 31
  • 141
  • 177
  • 1
    Your suggest help with date, but I can`t still figure out what is wrong with hours, minutes and seconds – georgevich Mar 24 '11 at 09:21
  • 7
    @george you don't miss anything. Those values are integers, so can't have value like "00". You can append it yourself easily for example `minute = (minute < 10 ? "0" : "") + minute;` – Shadow The GPT Wizard Mar 24 '11 at 09:28
  • @georgevich: in what timezone are you? What happens if you use `date.getUTCHours()`? – KooiInc Mar 24 '11 at 09:39
  • 1
    GMT + 2 The result of date.getUTCHours() is 19 – georgevich Mar 24 '11 at 09:43
  • GMT+2, so 22h universal time = 0h your time. Here's a jsfiddle using UTC-values: http://jsfiddle.net/EZFG9/. – KooiInc Mar 24 '11 at 09:49
  • and also `date.getMilliseconds()` for mili seconds. – Nabi K.A.Z. Nov 17 '17 at 20:44
  • And if you want a nicely formatted timestamp with leading zeroes: `timestamp = [date.getHours(), date.getMinutes(), date.getSeconds()].reduce(function (p, n) { return `${p}:${String(n).padStart(2, '0')}`; });` – Adam Grant Nov 12 '19 at 00:01
  • Why would you prefer `[...\`yyyy,mm,dd,hh,mmi,ss,mms\`.split(\`,\`)]` over `['yyyy','mm','dd','hh','mmi','ss','mms']`? No need to add operations and complexity. – Leo Aug 10 '22 at 13:01
  • 1
    @lenny I wouldn't say I prefer it. A remnant of old code perhaps. Removed it. – KooiInc Aug 11 '22 at 08:18
  • I was curious, maybe there was a hidden benefit or such :D – Leo Aug 11 '22 at 08:45
73
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
  • 45,245
  • 23
  • 243
  • 245
Shouvik
  • 11,350
  • 16
  • 58
  • 89
  • 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
  • 2
    `"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
11

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
  • 133
  • 1
  • 7
11

use Date.prototype.toLocaleTimeString() as documented here

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

Regolith
  • 2,944
  • 9
  • 33
  • 50
struggle4life
  • 111
  • 1
  • 2
10

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,376
  • 25
  • 24
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
  • 4,097
  • 2
  • 24
  • 46
7

To direct get a readable local timezone:

var timestamp = 1301090400,
date = new Date(timestamp * 1000)
document.write( date.toLocaleString() );
harrrrrrry
  • 13,643
  • 2
  • 23
  • 28
0

I'm too late to the party since this question is already a decade old, but I want to provide a cleaner one without the use of any plugins like moment.js. only vanilla javascript.

export default {
    // Accepts "1998-08-06 11:00:00" <-- This is UTC timestamp
    getFormalDateTime(utcDate) {
        const formattedUtc = utcDate.split(' ').join('T')+'Z'
        let date = new Date(formattedUtc);
        if (date.toString() === "Invalid Date")
            return "N/A";
    
        let dateString = date.toLocaleDateString("en-US", {month: 'long', day: 'numeric', year: 'numeric'});
        let timeString = date.toLocaleTimeString("en-US", {hour: 'numeric', minute: 'numeric', hour12: true});
        let formattedDate = dateString + " | " + timeString;
        return formattedDate; // Returns "August 6, 1998 | 11:00 AM" <-- This is converted to client time zone.
    },
    // Accepts: "1998-08-06"
    getFormalDate(convertDate) {
        let date = new Date(convertDate);
        if (date.toString() === "Invalid Date")
            return "N/A";

        let dateString = date.toLocaleDateString("en-US", {month: 'long', day: 'numeric', year: 'numeric'});
        return dateString // Returns "August 6, 1998"
    }
}

My code is formatted for ES6 modules because I use it as a module for my vuejs project but you can convert it to a normal javascript function.

getFormalDateTime('1998-08-06 11:00:00') the parameter should be in UTC time. This will return a formal date time converted to the client/browser timezone: August 6, 1998 | 11:00 AM

getFormalDate('1998-08-06') will just return August 6, 1998

More information here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString