SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Evangelist
    Join Date
    Jan 2005
    Posts
    425
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Simple Date object question

    How can I use a date that is stored in the format yyyymmdd, eg:19801228 to create a Date object?

    I've got access to jquery if that simplifies things.

    Thanks

  2. #2
    rajug.replace('Raju Gautam'); bronze trophy Raju Gautam's Avatar
    Join Date
    Oct 2006
    Location
    Kathmandu, Nepal
    Posts
    4,013
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    See some examples here:
    http://www.w3schools.com/jS/js_obj_date.asp
    http://www.tizag.com/javascriptT/javascriptdate.php

    Edit:
    Or just see some more results in google which I assume you have already done:
    http://www.google.com/search?hl=en&q=javascript+date

    And you need to split the string date so see substring function as well:
    http://www.w3schools.com/jsref/jsref_substring.asp
    Mistakes are proof that you are trying.....
    ------------------------------------------------------------------------
    PSD to HTML - SlicingArt.com | Personal Blog | ZCE - PHP 5

  3. #3
    SitePoint Guru
    Join Date
    Apr 2006
    Posts
    802
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Split the string, either with string.substring or a regular expression.
    You can make a 4 digit year string a number by prefixing a plus sign,
    but if the month or day is '08' or '09' it will convert to 10 or 11- (octal)
    parseInt(n,10) returns a decimal number from a string.

    Months in javascript are zero based- january is 0, not 1,
    so subtract 1 from the month field before you call the Date constructor.

    var s='19801228';
    var p=/^(\d{4})(\d{2})(\d{2})$/.exec(s);
    var y=parseInt(p[1],10), m=parseInt(p[2],10)-1,d=parseInt(p[3],10);
    alert(new Date(y,m,d));

    If you use substrings instead:
    var y=parseInt(s.substring(0,4),10),
    m=parseInt(s.substring(4,6),10)-1,
    d=parseInt(s.substring(6),10);
    alert(new Date(y,m,d));

  4. #4
    SitePoint Evangelist
    Join Date
    Jan 2005
    Posts
    425
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks, that worked great.


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
  •