var d ={
"title": "q",
"message": "q",
"date_time": "March 28, 2018 7:12 PM",
"user_id": "5abb6c929d5b611b01875e9b"
}
var s = d.date_time.split(',')
console.log(s)
5 Answers
If you don't want to add a library like moment.js, I'd suggest creating a native JavaScript Date object and working with that to extract whatever part you need from it.
const date = new Date(d.date_time);
console.log(`${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`);
console.log(`${date.getHours()}:${date.getMinutes()}`);
A couple of things to note:
- The return value of
getMonthis zero-based - You'll have to use your own logic to convert 24-hour to 12-hour AM/PM time if that's required
- Beware of time zones
Comments
You can use the js plugin moment.js:
var dateStr = moment(d.date_time).format('LL');
var timeStr = moment(d.date_time).format('LT');
See here for info: https://momentjs.com
If you need an array then just do this: var cars = [dateStr, timeStr];
5 Comments
Rajesh Kumar J
i need a solution to split the March 28, 2018 7:12 PM as ['March 28, 2018','7:12 PM'] can anyone help with regular expression
G43beli
what do you mean with "we can't update"? you don't need to update the database. I just decalared to variables, one for the time and one for the date
G43beli
if you need regex than please write your question properly
Rajesh Kumar J
i'm new to the stackoverflow...sorry
G43beli
@RajeshKumarJ I added an extension to my answer. The result will be the same: ['March 28, 2018','7:12 PM']
You can use regular expression
myArray = /(\w+ \d+), (\d+) (\d+):(\d+) (\w+)/g.exec('March 28, 2018 7:12 PM');
You will get array of
0:"March 28, 2018 7:12 PM"
1:"March 28"
2:"2018"
3:"7"
4:"12"
5:"PM"
You can work with that.
Or if you need to just split date and time use:
myArray = /(\w+ \d+, \d+) (\d+:\d+ \w+)/g.exec('March 28, 2018 7:12 PM');
Your result will be:
0:"March 28, 2018 7:12 PM"
1:"March 28, 2018"
2:"7:12 PM"
Comments
var d ={
"title": "q",
"message": "q",
"date_time": "March 28, 2018 7:12 PM",
"user_id": "5abb6c929d5b611b01875e9b"
};
var data = d.date_time.split(' ');
var date = data[0]+' '+data[1]+' '+data[2];
var time = data[3]+' '+data[4];
console.log(date);
console.log(time);
Split the string with space , then get the data.
Comments
var d ={
"title": "q",
"message": "q",
"date_time": "March 28, 2018 7:12 PM",
"user_id": "5abb6c929d5b611b01875e9b"
},
new_date_time = new Date( d.date_time ),
s = new_date_time.toLocaleDateString(),
t = new_date_time.toLocaleTimeString();
console.log('Date: ' + s );
console.log('Time: ' + t )
var datetime = new Date(d.date_time);you can split whatever you need from there. Also Momentjs is very easy to use and can do a lot with dates.