263

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.

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.

Penny Liu
  • 15,447
  • 5
  • 79
  • 98
Andrew
  • 12,172
  • 16
  • 46
  • 61
  • 5
    if you don't want to have local time, then why you use javascript for it? shouldn't you do it at server? – fazo Jan 12 '11 at 20:14
  • 1
    Check this library out -> http://www.datejs.com/ (Check out toString()) – Ryan Jan 12 '11 at 20:15
  • @fazo - This was more or less a project intended to help me get better with JS, so I'm trying to use PHP as little as possible (hopefully only to read/write data to a file). – Andrew Jan 12 '11 at 20:17
  • 1
    I think he meant that he wants to format the time string accordingly? – Ryan Jan 12 '11 at 20:17
  • 2
    `?/?/1970 or whatever it is` -> [Unix Epoch](http://en.wikipedia.org/wiki/Unix_Epoch), `1970-01-01T00:00:00Z` – Camilo Martin Sep 13 '12 at 02:40

12 Answers12

383

var time = new Date().getTime(); // get your number
var date = new Date(time); // create Date object

console.log(date.toString()); // result: Wed Jan 12 2011 12:42:46 GMT-0800 (PST)
Kos
  • 4,890
  • 9
  • 38
  • 42
Brian Donovan
  • 8,274
  • 1
  • 26
  • 25
  • 18
    The OP was about converting from a number of milliseconds to a `Date` object, which is what the second line does. The first line is just a way of getting a sensible number of milliseconds. You could also just do `var date = new Date(0);`. – Brian Donovan Aug 21 '13 at 17:49
  • 4
    The time has to be a Number, not String – Nicolas S.Xu Jun 26 '17 at 00:48
168

If you want custom formatting for your date I offer a simple function for 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, !@phrogz.net
//*** 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);
};
Phrogz
  • 296,393
  • 112
  • 651
  • 745
59

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"
nyedidikeke
  • 6,899
  • 7
  • 44
  • 59
Ravindra Kumar
  • 1,842
  • 14
  • 23
23

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);
nyedidikeke
  • 6,899
  • 7
  • 44
  • 59
John K.
  • 5,426
  • 1
  • 21
  • 20
  • 5
    You do not need semi-colons in JavaScript. However, its best practice to use them. Sometimes, without them, the meaning of a statement can change (not in this case though). Some code reviewers zealously love them and fight for their presence. To keep things simple, its best to always use them. – Phil May 22 '16 at 20:25
17

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

BBTurtle
  • 171
  • 1
  • 3
8

Try using this code:

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

Enjoy it!

Kenlly Acosta
  • 547
  • 5
  • 10
5

so you need to pass that var time after getTime() into another new Date() here is my example:

var time = new Date()
var time = time.getTime()
var newTime = new Date(time)
console.log(newTime)
//Wed Oct 20 2021 15:21:12 GMT+0530 (India Standard Time)

here output is my datetime standard format for you it will be in country format

if you want it in another format then you can apply another date function on var newTime like

var newTime = new Date(time).toDateString()
console.log(newTime)
//Wed Oct 20 2021
HiddenOne1254
  • 146
  • 1
  • 6
3

Try this one :

var time = new Date().toJSON();
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
abhi
  • 189
  • 4
2

One line code.

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

or

var date = new Date(1584120305684);
Ahmad Sharif
  • 4,141
  • 5
  • 37
  • 49
0
/Date(1383066000000)/

function convertDate(data) {
    var getdate = parseInt(data.replace("/Date(", "").replace(")/", ""));
    var ConvDate= new Date(getdate);
    return ConvDate.getDate() + "/" + ConvDate.getMonth() + "/" + ConvDate.getFullYear();
}
cezar
  • 11,616
  • 6
  • 48
  • 84
Joh
  • 11
  • 1
  • 3
    Try to explain why this answer solve the problem please, avoid just posting the code. – Ivan Mar 14 '18 at 10:59
0

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

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

For clearness see below code:

const theTime = new Date(1526813885836);
console.log(theTime.toString());
AmerllicA
  • 29,059
  • 15
  • 130
  • 154
-1

use datejs

new Date().toString('yyyy-MM-d-h-mm-ss');
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
smenon
  • 119
  • 2
  • 3