将毫秒转换为日期 (jQuery/JavaScript)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4673527/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 13:34:58  来源:igfitidea点击:

Converting milliseconds to a date (jQuery/JavaScript)

javascriptjquerydatetime

提问by Andrew

I'm a bit of a rambler, but I'll try to keep this clear -

我有点游手好闲,但我会尽量保持清楚——

I'm bored, so I'm working on a "shoutbox", and I'm a little confused over one thing. I want to get the time that a message is entered, and I want to make sure I'm getting the server time, or at least make sure I'm not getting the local time of the user. I know it doesn't matter, since this thing won't be used by anyone besides me, but I want to be thorough. I've looked around and tested a few things, and I think the only way to do this is to get the milliseconds since January 1, 1970 00:00:00 UTC, since that'd be the same for everyone.

我很无聊,所以我正在开发一个“留言箱”,我对一件事有点困惑。我想获取输入消息的时间,并且我想确保我正在获取服务器时间,或者至少确保我没有获取用户的本地时间。我知道没关系,因为这东西除了我以外不会被任何人使用,但我想彻底。我环顾四周并测试了一些东西,我认为唯一的方法是获取自19701 月 1 日 00:00:00 UTC以来的毫秒数,因为这对每个人都是一样的。

I'm doing that like so:

我是这样做的:

var time = new Date();
var time = time.getTime();

That returns a number like 1294862756114.

返回一个像1294862756114.

Is there a way to convert 1294862756114to a more readable date, like DD/MM/YYYY HH:MM:SS?

有没有办法转换1294862756114为更具可读性的日期,例如DD/MM/YYYY HH:MM:SS

So, basically, I'm looking for JavaScript's equivalent of PHP's date();function.

所以,基本上,我正在寻找与 PHPdate();函数等效的 JavaScript 。

回答by Brian Donovan

    var time = new Date().getTime();
    var date = new Date(time);
    alert(date.toString()); // Wed Jan 12 2011 12:42:46 GMT-0800 (PST)

回答by Phrogz

If you want custom formatting for your date I offer a simple functionfor it:

如果你想为你的日期自定义格式,我为它提供了一个简单的功能

var now = new Date;
console.log( now.customFormat( "#DD#/#MM#/#YYYY# #hh#:#mm#:#ss#" ) );

Here are the tokens supported:

以下是支持的令牌:

token:     description:             example:
#YYYY#     4-digit year             1999
#YY#       2-digit year             99
#MMMM#     full month name          February
#MMM#      3-letter month name      Feb
#MM#       2-digit month number     02
#M#        month number             2
#DDDD#     full weekday name        Wednesday
#DDD#      3-letter weekday name    Wed
#DD#       2-digit day number       09
#D#        day number               9
#th#       day ordinal suffix       nd
#hhhh#     2-digit 24-based hour    17
#hhh#      military/24-based hour   17
#hh#       2-digit hour             05
#h#        hour                     5
#mm#       2-digit minute           07
#m#        minute                   7
#ss#       2-digit second           09
#s#        second                   9
#ampm#     "am" or "pm"             pm
#AMPM#     "AM" or "PM"             PM

And here's the code:

这是代码:

//*** This code is copyright 2002-2016 by Gavin Kistner, [email protected]
//*** It is covered under the license viewable at http://phrogz.net/JS/_ReuseLicense.txt
Date.prototype.customFormat = function(formatString){
  var YYYY,YY,MMMM,MMM,MM,M,DDDD,DDD,DD,D,hhhh,hhh,hh,h,mm,m,ss,s,ampm,AMPM,dMod,th;
  YY = ((YYYY=this.getFullYear())+"").slice(-2);
  MM = (M=this.getMonth()+1)<10?('0'+M):M;
  MMM = (MMMM=["January","February","March","April","May","June","July","August","September","October","November","December"][M-1]).substring(0,3);
  DD = (D=this.getDate())<10?('0'+D):D;
  DDD = (DDDD=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][this.getDay()]).substring(0,3);
  th=(D>=10&&D<=20)?'th':((dMod=D%10)==1)?'st':(dMod==2)?'nd':(dMod==3)?'rd':'th';
  formatString = formatString.replace("#YYYY#",YYYY).replace("#YY#",YY).replace("#MMMM#",MMMM).replace("#MMM#",MMM).replace("#MM#",MM).replace("#M#",M).replace("#DDDD#",DDDD).replace("#DDD#",DDD).replace("#DD#",DD).replace("#D#",D).replace("#th#",th);
  h=(hhh=this.getHours());
  if (h==0) h=24;
  if (h>12) h-=12;
  hh = h<10?('0'+h):h;
  hhhh = hhh<10?('0'+hhh):hhh;
  AMPM=(ampm=hhh<12?'am':'pm').toUpperCase();
  mm=(m=this.getMinutes())<10?('0'+m):m;
  ss=(s=this.getSeconds())<10?('0'+s):s;
  return formatString.replace("#hhhh#",hhhh).replace("#hhh#",hhh).replace("#hh#",hh).replace("#h#",h).replace("#mm#",mm).replace("#m#",m).replace("#ss#",ss).replace("#s#",s).replace("#ampm#",ampm).replace("#AMPM#",AMPM);
};

回答by Ravindra

You can simply us the Datejslibrary in order to convert the date to your desired format.

您可以简单地使用Datejs库将日期转换为您想要的格式。

I've run couples of test and it works.

我已经运行了几个测试并且它有效。

Below is a snippet illustrating how you can achieve that:

下面是一个片段,说明如何实现这一目标:

var d = new Date(1469433907836);

d.toLocaleString(); // expected output: "7/25/2016, 1:35:07 PM"

d.toLocaleDateString(); // expected output: "7/25/2016"

d.toDateString();  // expected output: "Mon Jul 25 2016"

d.toTimeString(); // expected output: "13:35:07 GMT+0530 (India Standard Time)"

d.toLocaleTimeString(); // expected output: "1:35:07 PM"

回答by John K.

Below is a snippet to enable you format the date to a desirable output:

下面是一个片段,使您能够将日期格式化为所需的输出:

var time = new Date();
var time = time.getTime();

var theyear = time.getFullYear();
var themonth = time.getMonth() + 1;
var thetoday = time.getDate();

document.write("The date is: ");
document.write(theyear + "/" + themonth + "/" + thetoday);

回答by BBTurtle

Try using this code:

尝试使用此代码:

var datetime = 1383066000000; // anything
var date = new Date(datetime);
var options = {
        year: 'numeric', month: 'numeric', day: 'numeric',
    };

var result = date.toLocaleDateString('en', options); // 10/29/2013

See more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString

查看更多:https: //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString

回答by Kenlly Acosta

Try using this code:

尝试使用此代码:

var milisegundos = parseInt(data.replace("/Date(", "").replace(")/", ""));
var newDate = new Date(milisegundos).toLocaleDateString("en-UE");

Enjoy it!

好好享受!

回答by abhi

Try this one :

试试这个:

var time = new Date().toJSON();

回答by smenon

use datejs

使用日期js

new Date().toString('yyyy-MM-d-h-mm-ss');

回答by Joh

/Date(1383066000000)/

function convertDate(data) {
    var getdate = parseInt(data.replace("/Date(", "").replace(")/", ""));
    var ConvDate= new Date(getdate);
    return ConvDate.getDate() + "/" + ConvDate.getMonth() + "/" + ConvDate.getFullYear();
}

回答by AmerllicA

Assume the date as milliseconds date is 1526813885836, so you can access the date as string with this sample code:

假设日期为毫秒日期1526813885836,因此您可以使用以下示例代码以字符串形式访问日期:

console.log(new Date(1526813885836).toString());

For clearness see below code:

为清楚起见,请参阅以下代码:

const theTime = new Date(1526813885836);
console.log(theTime.toString());