2

I have this value

"6/19/2012 5:16:26 PM"

I am wanting to always only show the date and never the time

result i want

"6/19/2012"

I was trying things like this but it is not at all what i want

var myDate="26-02-2012";
myDate=myDate.split("-");
var newDate=myDate[1]+","+myDate[0]+","+myDate[2];
alert(new Date(newDate).getTime());​

5 Answers5

2

Try this:

alert(new Date().toJSON().slice(0,10));

JSFIDDLE DEMO

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
2

I am wanting to always only show the date and never the time

result i want

"6/19/2012"

Try using .split() with RegExp /\s/ , alternatively with String " " selecting item at index 0 of resulting array

  var str = "6/19/2012 5:16:26 PM";
  var date = str.split(/\s/)[0]; // `str.split(" ")[0]`
guest271314
  • 1
  • 15
  • 104
  • 177
1

use default constructor of Date

var date = new Date('6/19/2012 5:16:26 PM')
date .getMonth() + "/" date .getDay() + "/" + date .getYear()
Omidam81
  • 1,887
  • 12
  • 20
1

How about this, the output depends on your local settings, is short, uses the Javascript Date API and no String manipulation is needed.

(new Date("6/19/2012 5:16:26 PM")).toLocaleDateString() // Output => "6/19/2012"

Here a link to the Documentation

And Here a Demo:

document.write((new Date).toLocaleDateString()); // Output => "10/13/2015"    
document.write("<br />");
document.write((new Date("6/19/2012 5:16:26 PM")).toLocaleDateString());  // Output => "6/19/2012"
// tested on Win7 with Chrome 45+
winner_joiner
  • 12,173
  • 4
  • 36
  • 61
0

result i want

"6/19/2012"

If that's really what you want, then it's a string, so it's just:

var result = "6/19/2012 5:16:26 PM".split(" ")[0];

Live Example:

document.body.innerHTML = "6/19/2012 5:16:26 PM".split(" ")[0];

But if you want an actual Date instance, instead of using the one-argument version of Date, use the multi-argument version (accepts year, month, day, ...):

var myDate="6/19/2012 5:16:26 PM";
myDate=myDate.split(" ")[0].split("/");
alert(new Date(parseInt(myDate[2], 10), parseInt(myDate[0], 10) - 1, parseInt(myDate[1], 10)));​

Live Example:

var myDate = "6/19/2012 5:16:26 PM";
myDate = myDate.split(" ")[0].split("/");
document.body.innerHTML = new Date(parseInt(myDate[2], 10), parseInt(myDate[0], 10) - 1, parseInt(myDate[1], 10));

The parseInt(..., 10) converts from string to number using base 10 (decimal), and that builds a date from just the year, month (they start at 0), and day.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875