0

Sorry, but what is the fastest way to display the current date?

 2014-01-18 Saturday 12:30

with this function or how do it the right way?

 var d=new Date();
 var t=d.getTime();
poppel
  • 1,543
  • 4
  • 17
  • 22
  • 1
    `Date().valueOf();` [Date MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) – Givi Jan 18 '14 at 11:30
  • 1
    Also, look at [Where can I find documentation on formatting a date in JavaScript](http://stackoverflow.com/questions/1056728/where-can-i-find-documentation-on-formatting-a-date-in-javascript) – Givi Jan 18 '14 at 11:37

4 Answers4

2

Try

var d = new Date();
var dd = d.getDate();
var mm = d.getMonth()+1; //January is 0!
var yy = d.getFullYear();

var weekday=new Array(7);
weekday[0]="Sunday";
weekday[1]="Monday";
weekday[2]="Tuesday";
weekday[3]="Wednesday";
weekday[4]="Thursday";
weekday[5]="Friday";
weekday[6]="Saturday";

var day=weekday[d.getDay()];

var h = d.getHours();
    var m = d.getMinutes();

alert(yy+"-"+mm+"-"+dd+" "+day+" "+h+":"+m)

DEMO

laaposto
  • 11,835
  • 15
  • 54
  • 71
1

If you don't mind the format, you can do it in one line:

''+new Date()

You only need to use a Date object as a string, in order to implicitly call its .toString() method, which

returns a String value. The contents of the String are implementation-dependent, but are intended to represent the Date in the current time zone in a convenient, human-readable form.

Oriol
  • 274,082
  • 63
  • 437
  • 513
1
var d =  new Date();
alert(d.toString());
Vivek
  • 4,786
  • 2
  • 18
  • 27
  • 1
    Just a note: there's no need to explicitly use `.toString()` – Oriol Jan 18 '14 at 11:36
  • true but here I have just given `.toString()` for to be in safe side. I assumed there would be further operations on the variable like storing in some other variable or smthing.... So depends on the use case – Vivek Jan 18 '14 at 11:51
1
new Date().toGMTString()

It's something similar to what you are looking for

If you want complicate the output you can get element by element and format yourself the date (or you can use Globalize.js)

franco
  • 133
  • 2
  • 10