user5299399
user5299399

Reputation:

Parse Date and Time String to only use the Date in Javascript

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());​

Upvotes: 2

Views: 272

Answers (5)

guest271314
guest271314

Reputation: 1

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]`

Upvotes: 2

winner_joiner
winner_joiner

Reputation: 14695

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+

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074028

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.

Upvotes: 0

Omidam81
Omidam81

Reputation: 1917

use default constructor of Date

var date = new Date('6/19/2012 5:16:26 PM')
date .getMonth() + "/" date .getDay() + "/" + date .getYear()

Upvotes: 1

Rahul Tripathi
Rahul Tripathi

Reputation: 172378

Try this:

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

JSFIDDLE DEMO

Upvotes: 2

Related Questions