Converting milliseconds to a date (jQuery/JavaScri

2019-01-01 06:36发布

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 ?/?/1970 or whatever it is, since that'd be the same for everyone.

I'm doing that like so:

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

That returns a number like 1294862756114.

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

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

10条回答
无色无味的生活
2楼-- · 2019-01-01 07:04

Try this one :

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

查看更多
浮光初槿花落
3楼-- · 2019-01-01 07:06

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

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"
查看更多
若你有天会懂
4楼-- · 2019-01-01 07:08

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

查看更多
倾城一夜雪
5楼-- · 2019-01-01 07:10

Try using this code:

var milisegundos = parseInt(data.replace("/Date(", "").replace(")/", ""));

var newDate = new Date(milisegundos).toLocaleDateString("en-UE");

Enjoy it!

查看更多
牵手、夕阳
6楼-- · 2019-01-01 07:18
/Date(1383066000000)/

function convertDate(data) {
    var getdate = parseInt(data.replace("/Date(", "").replace(")/", ""));
    var ConvDate= new Date(getdate);
    return ConvDate.getDate() + "/" + ConvDate.getMonth() + "/" + ConvDate.getFullYear();
}
查看更多
无色无味的生活
7楼-- · 2019-01-01 07:21

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

查看更多
登录 后发表回答