SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Member
    Join Date
    Jun 2010
    Posts
    12
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Convert string to date

    Consider this scenario,

    I have a string,
    var sDate = '11-07-2010';

    var date = new Date(sDate);

    var day = date.getDay();
    alert(day);

    here I need to know the day based on this date. But the string is not gettin converted to date and hence the result that i get is NaN. Can someome please help me on this issue? I need the logic in javascript
    Last edited by sanilsunny; Jul 20, 2010 at 03:56. Reason: Javascript

  2. #2
    SitePoint Enthusiast TriLLi's Avatar
    Join Date
    Feb 2010
    Location
    BiH, Bugojno
    Posts
    86
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    var sDate = '11-07-2010'.split('-');
    sDate = sDate[2] + '-'+sDate[1]+'-'+sDate[0];


    var date = new Date(sDate);
    http://www.wiseblog.info
    Programmers don't die, they just GO SUB without return.

  3. #3
    SitePoint Guru
    Join Date
    Apr 2006
    Posts
    802
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Your date string is ambiguous.

    No timezone is indicated, so you may intend to use the user's local time,
    which will make it a different absolute date depending on where the user is at the time.

    It could also mean november 7 or july 11, depending on the local formatting.

    If you want to return july 11,2010, local time,
    split the string into an array of numbers
    and use the Date constructor- new Date (yyyy, mm-1, dd).

    Months are zero indexed.

    Code:
    var d, nDate, sDate= '11-07-2010';
    
    d=sDate.split('-');
    
    d[0]= parseInt(d[0],10);
    d[1]= parseInt(d[1],10)-1;
    d[2]= parseInt(d[2],10);
    
    var nDate = new Date(d[2],d[1],d[0]);
    //test
    Code:
    alert(nDate);
    
    /*  returned value: (local Date)
    Sun Jul 11 2010 00:00:00 GMT-0400 (Eastern Daylight Time)
    */
    
    alert(nDate.getDay())
    /*  returned value: (Number)
    0
    */


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •