function - How can I convert a string converted using toLocaleString() in javascript back to Date Object? -
i using javascript function tolocalestring() convert date object string (as it's output user friendly), storage purpose, , want fetch saved data (obviously in form of string) later, , want compare such dates.
i have date stored in format : february 5, 2016 7:04:40 pm ist
but that's not possible directly, tried convert string date object using both implicit (using date constructor) , explicit (using date object) methods. gives invalid date, output, when printed. google lot find out how can convert date format directly date object can perform desired date operations. couldn't found worth using. please me came out solution problem, can complete project.
if need use pure javascript should create function parses string in order use arguments create date object.
var months = { 'january': 0, 'february': 1, 'march': 2, 'april': 3, 'may': 4, 'june': 5, 'july': 6, 'august': 7, 'september': 8, 'october': 9, 'november': 10, 'december': 11, }; var strdate = "february 5, 2016 7:04:40 pm ist"; var parts = strdate.split(' '); var year = parts[2]; var month = months[parts[0].tolowercase()]; var day = parts[1].replace(/\,/g,""); var timeparts = parts[3].split(':'); var hours = timeparts[0]; var minutes = timeparts[1]; var seconds = timeparts[2]; if (parts[4]==="pm") { hours = parseint(hours) + 12; } var d = new date(year, month, day, hours, minutes, seconds); alert(d.tolocalestring());
in futur please put little more efforts it. could've written yourself.
edit 2 : none of needed. can use date.parse() function long if remove ist end.
var strdate = "february 5, 2016 7:04:40 pm"; var d = new date("february 5, 2016 7:04:40 pm"); alert(d.tolocalestring());
then if want can set timezone manually.
Comments
Post a Comment