0

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

I know I can achieve this by a regular expression, but is there a built-in function that can do this?

3 Answers 3

3

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 regular expression or string manipulation in this case.

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

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) {
    // This function parses SQL datetime string and returns a JavaScript Date object
    // The 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.

Sign up to request clarification or add additional context in comments.

1 Comment

@Shore - Please accept my answer so that this question does not remain as unanswered in stackoverflow.
0

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>

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.