Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 271
SteveV Avatar asked Oct 15 '25 11:10

SteveV


2 Answers

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*/, ":");

like image 120
buræquete Avatar answered Oct 16 '25 23:10

buræquete


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" 
like image 32
twernt Avatar answered Oct 17 '25 01:10

twernt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!