I am new to javascript and trying to get parts of the string and format it.
I have a string:
update_time="THU 2017-06-29 23:41:13 ET"
I want to get and format the date to look like: 06/29/2017
Any help would be appreciated
I am new to javascript and trying to get parts of the string and format it.
I have a string:
update_time="THU 2017-06-29 23:41:13 ET"
I want to get and format the date to look like: 06/29/2017
Any help would be appreciated
You have a str.substr(Begin, Length)
method in javascript. The following code will give you the right parts of the string.
update_time="THU 2017-06-29 23:41:13 ET"
new_format = update_time.substr(9,2) + '/' + update_time.substr(12,2) + '/' + update_time.substr(4,4)
The result being a var new_format
with the string 06/29/2017
.
You could use this regular expression. It detects anything formatted as yyyy-dd-mm and formats it as dd/mm/yyyy
new_time = update_time.replace(/.*(\d{4})-(\d{2})-(\d{2}).*/, "$2/$3/$1");
If you want to keep the original string in place, but just change the date, then remove the .*
from both sides.
best will be to split
it with whitespace and then, take the second element and construct a date and use toLocaleDateString()
new Date(update_time.split(' ')[1]).toLocaleDateString()
function getDateFormat(data){
if (!data) return null;
let dateObj = new Date(parseInt(data));
let date = dateObj.getDate();
let month = dateObj.getMonth();
let year = dateObj.getFullYear();
let time = dateObj.getHours();
let minutes = dateObj.getMinutes();
let seconds = dateObj.getSeconds();
if (time > 12){
time = time - 12;
time = time + ':' + minutes + ':' + seconds + ' PM';
}else{
time = time + ':' + minutes + ':' + seconds + ' AM';
}
date = date + ' - ' + month + ' - ' + year;
return {
date: date,
time: time
}
}
This function not working in date string.
If you have date in milliseconds, you can use my method to get date and time properly.
Just pass milliseconds to my function it returns a object that contains date and time.
You can use defaults JavaScript functions:
var update_time="THU 2017-06-29 23:41:13 ET"
Updates: As RobG explained we can't parse only with the Date object. So we can either use the regular expression or split Function
var dateComponents = update_time.split(' ')[1].split('-'); //["2017", "06", "29"]
var formatedDate = `${dateComponents[1]}/${dateComponents[2]}/${dateComponents[0]}`;
console.log(formatedDate);
Or optionally you can use the momentJs library.