Reputation: 323
var date ="03/05/2013";
var localDate = date.split("/").reverse().join("-");
var localTime = "20:41"
var UTCDateTime = localDate+ "T" + localTime +":00.000Z";
localDateTime = new Date(UTCDateTime)
var options = { hour12: false, day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute:'2-digit' };
console.log("Date:>>"+localDateTime.toLocaleString('en', options));
How do you remove comma after date Date:>>05/03/2013 21:41
Upvotes: 23
Views: 31052
Reputation: 51
You can use the Intl.DateTimeFormat
function for your desired locale for this. Try the following code:
const date = new Date(Date.UTC(2022, 02, 17, 12, 48, 00));
const formatter = new Intl.DateTimeFormat('en', {dateStyle: 'short', timeStyle: 'medium', hour12: false});
const arr = formatter.format(date).split(',');
const ans = `${arr[0]}${arr[1]}`;
console.log(ans);
Upvotes: 3
Reputation: 2290
I wouldn't replace the comma with either the replace
function or a regex, because that could easily result in the wrong commas being removed. The short date format that you use in your example doesn't contain a comma in the date part, but a longer date format like { day: '2-digit', month: 'long', year: 'numeric', hour: '2-digit', minute:'2-digit' }
will.
A more resilient option is to format the date and time parts separately, and concatenate them with a space in between:
var date ="03/05/2013";
var localDate = date.split("/").reverse().join("-");
var localTime = "20:41"
var UTCDateTime = localDate+ "T" + localTime +":00.000Z";
localDateTime = new Date(UTCDateTime)
var dateOptions = { day: '2-digit', month: '2-digit', year: 'numeric' };
var timeOptions = { hour12: false, hour: '2-digit', minute:'2-digit' };
console.log("Date:>>" + localDateTime.toLocaleDateString('en', dateOptions) + " " + localDateTime.toLocaleTimeString('en', timeOptions));
Upvotes: 18
Reputation: 22167
What's about using regex?
'01/01/2018, 12:00'.replace(/^(\d{2})\/(\d{2})\/(\d{4}), (\d{2}):(\d{2})/, '$1/$2/$3 $4:$5')
var date = '03/05/2013';
var localDate = date.split('/').reverse().join('-');
var localTime = '20:41';
var localDateTime = new Date(localDate+ 'T' + localTime + ':00.000Z');
var options = {hour12: false, day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute:'2-digit'};
var output = localDateTime.toLocaleString('en', options);
var outputFormatted = output.replace(/^(\d{2})\/(\d{2})\/(\d{4}), (\d{2}):(\d{2})/, '$1/$2/$3 $4:$5');
console.log(outputFormatted);
Upvotes: 3
Reputation: 6646
With replace
:
var date ="03/05/2013";
var localDate = date.split("/").reverse().join("-");
var localTime = "20:41"
var UTCDateTime = localDate+ "T" + localTime +":00.000Z";
localDateTime = new Date(UTCDateTime)
var options = { hour12: false, day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute:'2-digit' };
console.log("Date:>>"+localDateTime.toLocaleString('en', options).replace(',',''));
Upvotes: 10