Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 512
kirbyjwilson Avatar asked May 15 '12 20:05

kirbyjwilson


People also ask

How do you convert date format from Yyyymmdd to yyyy mm dd in SQL?

Convert Char 'yyyymmdd' back to Date data types in SQL Server. Now, convert the Character format 'yyyymmdd' to a Date and DateTime data type using CAST and CONVERT. --A. Cast and Convert datatype DATE: SELECT [CharDate], CAST([CharDate] AS DATE) as 'Date-CAST', CONVERT(DATE,[CharDate]) as 'Date-CONVERT' FROM [dbo].


2 Answers

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.

like image 56
firexfighterx Avatar answered Oct 04 '22 18:10

firexfighterx


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 
like image 31
timrwood Avatar answered Oct 04 '22 17:10

timrwood