Arushi
Arushi

Reputation: 137

How to get last word from string In jquery

I am Getting a String Like:

Mon Jul 10 2017 03:00:00 GMT+0000

I want To use Only 03:00 from the string in jQuery. How Can I split the string to get this through jQuery Or JavaScript?

I want only time from The result.

Upvotes: 0

Views: 563

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337560

You're using the incorrect approach. You don't want to start hacking this string around. Instead, convert it to a Date object then get the hours and minutes from it:

var date = new Date('Mon Jul 10 2017 03:00:00 GMT+0000');
var time = ('00' + date.getUTCHours()).slice(-2) + ':' + ('00' + date.getUTCMinutes()).slice(-2);
console.log(time);

Upvotes: 1

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167162

Well, this is not a normal string, but a time string. You might need to parse it and then get the hours and minutes:

var str = "Mon Jul 10 2017 03:00:00 GMT+0000";
var time = new Date(str);
console.log(("0" + time.getHours()).substr(-2) + ":" + ("0" + time.getMinutes()).substr(-2));

Upvotes: 0

Related Questions