views:

254

answers:

3

To make time like "2009-05-02 00:00:00" to "2009-05-02"

I know I can achieve this by regular expression,

but would be better if there is a built-in function that can do this.

+3  A: 

There's no built-in date function that can do that. As a matter of fact if you create a new Date object in javascript with that date format, you get an Invalid Date Error.

You are correct in using a RegEx or string manipulation in this case.

Here's a list of all the Javascript Date Functions.

UPDATE: To simply get the date portion of the string and display it without converting into a Date Object. You can simply do this:

var dateString = "2009-05-02 00:00:00"
alert(dateString.substring(0,10)); //will show "2009-05-02"

To convert this string into a proper Javascript Date Object, you can use this snippet:

function sqlTimeStampToDate(timestamp) {
    //function parses sql datetime string and returns javascript Date object
    //input has to be in this format: 2007-06-05 15:26:02
    var regex=/^([0-9]{2,4})-([0-1][0-9])-([0-3][0-9]) (?:([0-2][0-9]):([0-5][0-9]):([0-5][0-9]))?$/;
    var parts=timestamp.replace(regex,"$1 $2 $3 $4 $5 $6").split(' ');
    return new Date(parts[0],parts[1]-1,parts[2],parts[3],parts[4],parts[5]);
  }

The format will be "ddd MMM dd YYYY hh:mm:ss" + TimeOffSet, but you will be able to use any of the standard javascript date functions.

Jose Basilio
Hey, you're right :) . +1.http://snippets.dzone.com/posts/show/4132
Alterlife
@Shore - did this answer help you?
Jose Basilio
@Shore - Please accept my answer so that this question does not remain as *unanswered* in stackoverflow.
Jose Basilio
A: 

You might find this helpful:

"Return today's date and time How to use the Date() method to get today's date.

getTime() Use getTime() to calculate the years since 1970. setFullYear() How to use setFullYear() to set a specific date.

toUTCString() How to use toUTCString() to convert today's date (according to UTC) to a string.

getDay() Use getDay() and an array to write a weekday, and not just a number."

This is copy-paste from www.w3schools.com since I can't post a link to it...

Or just search google for "javascript date function" or related. Regular expressions are used to match specific parts of strings, which is useful in searching, extraction and replacement, not really anything that would help you with formatting a date.

A: 

See below for two simple methods to get a date format of "2009-05-02", from the initial format, that is "2009-05-02 00:00:00".

<script type="text/javascript">
var mydate, newdate1, newdate2;

mydate = "2009-05-02 00:00:00";

newdate1 = (mydate.split(/ /))[0];
alert('newdate 1: ' + newdate1);

newdate2 = mydate.substr(0,10);
alert('newdate 2: ' + newdate2);
</script>
Fran Corpier