开发者

Timestamp to human readable format

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开发者_C百科 00. But it is 2011, 2, 6, 0, 0, 0 What I miss ?


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).


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


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


use Date.prototype.toLocaleTimeString() as documented here

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


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


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)


To direct get a readable local timezone:

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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜