SteveV
SteveV

Reputation: 441

Remove space in a date string

I'm getting a date from a database that sometimes has spaces in the times (there isn't a way to clean up DB as I don't have control). I need to remove the spaces so I can format it to a Javascrpt date.

For example:

5 : 03 PM 

As you can see, this is incorrect. I've looked at Moment.js and Regex to remove spaces around the colon, but not sure how that's done or if that's the proper way. Is there a way to remove this space?

Thanks all!

Upvotes: 4

Views: 5811

Answers (3)

Sukima
Sukima

Reputation: 10074

For completeness you could aviod regexp:

'5  :  03pm'.split(':')
  .map(function(part) { return part.trim(); })
  .join(':');

Upvotes: 1

buræquete
buræquete

Reputation: 14688

Only to delete the space around the colon, try the following; (where $1 refers to the first capture group, that is the only one (:))

a.replace(/\s*(:)\s*/, "$1");

or if you wish to simplify it further, without any capturing group;

a.replace(/\s*:\s*/, ":");

Upvotes: 6

twernt
twernt

Reputation: 20591

If you want to, you can actually parse that date string with Moment.js, you just need to include the spaces in your formatting string:

var time = moment('5 : 03 PM', 'h : m A');

Then you can format it however you want:

time.format('h:mmA'); // "5:30PM"
time.format('hh:mm A'); // "05:03 PM"
time.format('HH:mm'); // "17:03" 

Upvotes: 6

Related Questions