Timestamp to human readable format

JavascriptTimestamp

Javascript Problem Overview


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 ?

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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() );

Solution 3 - Javascript

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

Solution 4 - Javascript

use Date.prototype.toLocaleTimeString() as documented here

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

Solution 5 - Javascript

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)

Solution 6 - Javascript

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

Solution 7 - Javascript

To direct get a readable local timezone:

var timestamp = 1301090400, date = new Date(timestamp * 1000) document.write( date.toLocaleString() );

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiongeorgevichView Question on Stackoverflow
Solution 1 - JavascriptKooiIncView Answer on Stackoverflow
Solution 2 - JavascriptShouvikView Answer on Stackoverflow
Solution 3 - JavascriptgolakersView Answer on Stackoverflow
Solution 4 - Javascriptstruggle4lifeView Answer on Stackoverflow
Solution 5 - JavascriptHosseinView Answer on Stackoverflow
Solution 6 - JavascriptDaveAlgerView Answer on Stackoverflow
Solution 7 - JavascriptharrrrrrryView Answer on Stackoverflow