I have this time in a variable called lastdate in javascript.
07:31:00
How can I show AM or PM using format specifier in Javascript..Like I use in php "%p" . Is there any method to use in javascript. Any help is much appreciated.
I have this time in a variable called lastdate in javascript.
07:31:00
How can I show AM or PM using format specifier in Javascript..Like I use in php "%p" . Is there any method to use in javascript. Any help is much appreciated.
Assuming that your time string will be in 24H format:
1.) Split time string into array.
2.) Create new Date object.
3.) Map the array to create integers. (this can also be done on each variable in the below method)
4.) Set the hours, minutes, and seconds to values of the generated array.
5.) Convert Date object to the local time string and use a Regex to create your new time string. (NOTE: toLocaleTimeString() may behave differently based on location)
/* Variable Defaults */
var timeString = '07:31:00';
var parts = timeString.match(/(\d{2}):(\d{2}):(\d{2})/);
var dateObject = new Date();
/* Cast `parts` as Integer */
Object.keys(parts).map(function(key, index) {
parts[key] = parseInt(parts[key]);
});
/* Set Hours/Minutes/Seconds */
dateObject.setHours(parts[1]);
dateObject.setMinutes(parts[2]);
dateObject.setSeconds(parts[3]);
/* Output New String */
var newTimeString = dateObject.toLocaleTimeString().replace(/([\d]+:[\d]{2})(:[\d]{2})(.*)/, '$1$3')
/* Console Result */
console.log(newTimeString);
If you can bring in an external library, I'd recommend moment.js.
Then you can specify what you want with:
var lastdate = "07:31:00"
moment(lastdate, 'HH:mm:ss').format('LTS'); // 07:31:00 AM
Or if you want to be more explicit:
var lastdate = "07:31:00"
moment(lastdate, 'HH:mm:ss').format('HH:mm:ss A'); // 07:31:00 AM
Where the A means AM/PM. See https://momentjs.com/docs/#/displaying/format/.