Reputation: 1439
I'm trying to parse time which is retrieved from MySql via jSon
something like:
new Date('12:15:24').toString('h:mmtt');
but I keep getting Invalid Date in console
What I need to do is convert 24 hour format into 12 hour am/pm and vice versa
Upvotes: 0
Views: 376
Reputation: 4197
it is better to use moment.js to handle datetime like this
// get hours:minutes:seconds of the date 31-Jan_2016 9.31.21
console.log(moment('2016-01-31 09:30:21').format('HH:mm:ss'))
// get current hours:minutes:seconds
console.log(moment().format('HH:mm:ss'))
// get current date-month-year hours:minutes:seconds
console.log(moment('2016-01-31 09:30:21').format('DD-MM-YYYY HH:mm:ss'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>
Upvotes: 0
Reputation: 12390
I would consider using date/time manipulation library, such as http://momentjs.com/ .
You can also achieve what you want by splitting the time string and creating a Date() object. Example:
var time = '12:15:24';
var timePortions = time.split(':');
new Date(0,0,0,timePortions[0], timePortions[1], timePortions[2])
This is not a safe way to manipulate date/time, though.
Upvotes: 0
Reputation: 150010
The Date()
constructor only likes a very restricted set of date formats. If your input format is fixed at 'hh:mm:ss'
it is probably easier to format it using a simple string replace:
function formatTime(time) {
return time.replace(/(\d?\d)(:\d\d):(\d\d)/, function(_, h, m) {
return (h > 12 ? h-12 : +h === 0 ? "12" : +h) + m + (h >= 12 ? "pm" : "am");
});
}
console.log( formatTime('00:15:24') );
console.log( formatTime('09:15:24') );
console.log( formatTime('10:15:24') );
console.log( formatTime('11:15:24') );
console.log( formatTime('12:15:24') );
console.log( formatTime('13:15:24') );
console.log( formatTime('14:15:24') );
Further reading:
Upvotes: 2