简体   繁体   中英

JavaScript New Date from a 12 hour format date and time string

Example string: 2014-12-31 11:59 pm

As it stands, JavaScript isn't even parsing the time as the resulting time code returns 12:00 am regardless of what time I provide.

Output after new Date("2014-12-31 11:59 pm") results in: 2014-12-31 12:00 am

EDIT:

Even after expecting a format and manually parsing the string, the new Date() constructor isn't behaving...

var sourceTime = "2014-12-31 11:59 pm";

var dateRaw = sourceTime.split(' ');
var dateYMD = dateRaw[0].split('-');
var dateTime = dateRaw[1].split(':');
var dateAmPm = dateRaw[2].toLowerCase();

// Adjust human month to system month...
dateYMD[1] = (parseInt(dateYMD[1]) - 1).toString();

// Convert 12h to 24h...
if(dateAmPm == 'pm') {
  if(parseInt(dateTime[0]) < 12) dateTime[0] = (parseInt(dateTime[0])+12).toString();
} else {
  if(parseInt(dateTime[0]) == 12) dateTime[0] = 0;
}

console.log(dateYMD);
console.log(dateTime);

var dateParsed = new Date(dateYMD[0], dateYMD[1], dateYMD[2], dateTime[0], dateTime[1]);

The console log shows the correct values being passed into new Date() but I'm still getting an incorrect output :(

Instead of using the standard Date from JavaScript I always use Moment.js when working with dates. It makes is very easy to work with different formats of dates and customizing everything.

In your case you could do something like:

var datestr = "2014-12-31 11:59 pm";
var date = moment(datestr,"YYYY-MM-DD HH:mm a")
$("#log").text(date.format("HH:mm:SS MMM DD YYYY"));

Here's a jsfiddle to try it.

As far as I know, there is no possibility to change the format of the Date String parsed by the Date constructor or Date.parse() in JavaScript. Format specifications can be found at RFC822 or ECMAScript Standards , and neither does support am/pm.

(links taken from MDN )

I'm fixed my problem.. Solution..

 let ThisDate = this.startDate0;
 let FinalYear = ThisDate.substring(6,10);
 let FinalMonth = ThisDate.substring(3,5);
 let FinalDay = ThisDate.substring(0,2);
 let FinalHour = ThisDate.substring(11, 13);
 let FinalMinutes = ThisDate.substring(14,16);
 let FinalDate = FinalYear + "-" + FinalMonth + "-" + FinalDay + " " + FinalHour + ":" + FinalMinutes;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM