开发者

Stumped on JS Epoch Convertion

开发者 https://www.devze.com 2023-02-03 17:44 出处:网络
In epoch 1265997351408 is Fri Feb 12 2010 12:55:51 GMT-0500 (EST) I am trying to write it as: February, 12 2010

In epoch 1265997351408 is Fri Feb 12 2010 12:55:51 GMT-0500 (EST)

I am trying to write it as: February, 12 2010

But I am getting: November, 10 42087

What am I doing wrong?

function makeHumanDate(epoch) {
   var theDate = epoch * 1000
   var months = new Array(13);
   months[0]  = "January";
   months[1]  = "February";
   months[2]  = "March";
   months[3]  = "April";
   months[4]  = "May";
   months[5]  = "June";
   months[6]  = "July";
   months[7]  = "August";
   months[8]  = "September";
   months[9]  = "October";
   months[10] = "November";
   months[11] = "December";
   var d           = new Date(theDate);
   var monthnumber = d.getUTCMonth();
   var monthname   = months[monthnumber];
   var monthday    = d.getUTCDate();
   var year        = d.getFullYear();
   if(year < 2000) { year = year + 1900; }
   var dateString 开发者_开发知识库= monthname +
                    ', ' +
                    monthday +
                    ' ' +
                    year;
   // Goal is: February, 12 2010
   return dateString;
}

I know its something dumb but I've been stuck for a while. Please Help.

Thanks!


You don't need to multiply epoch by 1000 in your example code - if you take this out, it works as expected :)

A little code clean-up

function makeHumanDate(epoch) {
   var months = ["January",
                 "February",
                 "March",
                 "April",
                 "May",
                 "June",
                 "July",
                 "August",
                 "September",
                 "October",
                 "November",
                 "December"],
       d = new Date(epoch),
       month = months[d.getUTCMonth()],
       day = d.getUTCDate(),
       year = d.getFullYear();

   // not needed as getFullYear returns the full year in 4 digits
   //if( year < 2000 ) year += 1900; 

   return month + ', ' + day + ' ' + year;
}


Your code is fine but your input is broken. If I use http://www.onlineconversion.com/unix_time.htm I get the same result you do.

Your timestamp seems to need a division by 1000 to get it back into a reasonable frame, after which I get the correct result.

0

精彩评论

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