简体   繁体   中英

How to split strings in javascript?

I want to split the datetime in the below object to date and time separately.

 let A = {
   datetime: '2019-02-01 15:30:43' 
 }

And save it in two different variables.

You can use split() eg

var splitString = A.datetime.split(" ");
// Returns array, ['2019-02-01','15:30:43']

You can access this with splitString[0] for the date and splitString[1] for the time.

You can use moment.js library if you don't want any surprises.

moment(A.datetime).format('L'); // get date only

moment(A.datetime).format('LTS') // get time only.

You can have specific date and time format as well when using momentjs .

You may also use JavaScript's Date class for this.

const date = new Date(A.datetime);

//to get date
date.getDate() +' '+date.getMonth()+' '+date.getFullYear();

//to get time.
date.getHours()+' '+date.getMinutes()+' '+date.getSeconds();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM