kirbyjwilson
kirbyjwilson

Reputation: 431

Convert Returned String (YYYYMMDD) to Date

I have a string that contains 8 digits that represent a date. For example:

20120515

I'd like to compare it with today's date, created in this manner:

var currentDate = new Date();

How can I convert the "8 digit date string" to a suitable date format in order to compare it to currentDate?

Upvotes: 43

Views: 69382

Answers (4)

ashleedawg
ashleedawg

Reputation: 21647

...some other "one-liner" ways to accomplish this:

(They take a value like dts='20020704'; and return date object [dt].)

var dt=new Date(dts.slice(0,4), (dts[4]+dts[5])-1, dts[6]+dts[7]);

...or...

var m=dts.match(/(....)(..)(..)/), dt=new Date(m[1],m[2]-1,m[3]);

...or...

var m=dts.match(/.{1,2}/g), dt=new Date(m[0]+m[1],m[2]-1,m[3]);

The last one's shortest, but the first is probably most efficient, since it doesn't use regex (but that's irrelevant, unless you're processing LOTS of data using this). I like the middle one best since it's easy to see what's happening.

Upvotes: 4

loretoparisi
loretoparisi

Reputation: 16311

To correctly handle the local time zone, it must explicitly summed to the calculated time

function dateStringToDate(dateString) {
  try {
    var year = dateString.substring(0, 4);
    var month = dateString.substring(4, 6);
    var day = dateString.substring(6, 8);
    var date = new Date(year, month - 1, day);
    const offset = date.getTimezoneOffset()
    date = new Date(date.getTime() - (offset * 60 * 1000));
    return date;
  } catch (error) {
    return null;
  }
}

function dateStringToDate(dateString) {
  try {
    var year = dateString.substring(0, 4);
    var month = dateString.substring(4, 6);
    var day = dateString.substring(6, 8);
    var date = new Date(year, month - 1, day);
    const offset = date.getTimezoneOffset()
    date = new Date(date.getTime() - (offset * 60 * 1000));
    return date;
  } catch (error) {
    return null;
  }
}

console.log(dateStringToDate("20211212"))
console.log(dateStringToDate("20211213"))
console.log(dateStringToDate("20211214"))

Upvotes: 2

firexfighterx
firexfighterx

Reputation: 679

Use the substring method and substring off 4 elements and assign it to your new date for the year. Then substring off two elements at a time and store the month and date accordingly.

var dateString  = "20120515";
var year        = dateString.substring(0,4);
var month       = dateString.substring(4,6);
var day         = dateString.substring(6,8);

var date        = new Date(year, month-1, day);
var currentDate = new Date();

Now you can compare the two dates with the normal operators.

Upvotes: 65

timrwood
timrwood

Reputation: 10681

If you want a small date library you can use moment.js.

var a = moment("20120515", "YYYYMMDD");
// then use any of moment's manipulation or display functionality
a.format("MMM Do YYYY"); // May 15th 2012
a.fromNow(); // 14 hours ago
a.calendar(); // Today at 12:00 AM

Upvotes: 25

Related Questions