简体   繁体   中英

How to convert the Full UTC time to yyyymmdd format using javascript

here how can i convert the

 [Sun Jul 15 2018 17:48:13 GMT+0530 (India Standard Time), Sun Jul 22 2018 17:48:13 GMT+0530 (India Standard Time)]

to 20180715 using javascript

here a variable named DateData is storing the above two dates DateData:Date[];

After selecting the from the datetime picker i storing the data in the DateData

now i am trying to convert the variable using DateData.toISOstring or DateData.toDate() also not working displaying as unable to convert the dataData to Date Format

Perhaps something like this

function sqlDate(dat)
{
  return dat.toISOString().substr(0,10).replace('-','');
}

There you go. :)

 function convertDates(dateArr) { var newDateArray = [], dateObj; for (var i=0; i<dateArr.length; i++) { dateObj = new Date(dateArr[i]); newDateArray.push(dateObj.getFullYear() + '' + dateObj.getMonth() + '' + dateObj.getDate()); } return newDateArray; } var dateArr = ['Sun Jul 15 2018 17:48:13 GMT+0530 (India Standard Time)', 'Sun Jul 22 2018 17:48:13 GMT+0530 (India Standard Time)']; console.log(convertDates(dateArr)); 

function formatDate(date){
    if(date instanceof Date) date = new Date(date);
    var fullZero = s => s.toString().length ===1 ?'0'+s :s.toString();
    return `${date.getFullYear()}${fullZero(date.getMonth()+1)}${fullZero(date.getDate())}`;
}

formatDate(new Date) // -> "20180722"

If you have an array of Date, use dateData.map(formatDate) to format it.

Try splitting on the "T" like this snippet:

 var d = new Date(); // => d.toISOString() show 2019-02-01T06:38:21.990Z console.log(d.toISOString().split("T")[0].replace(/-/g, '')); 

or you can use a JavaScript library called date-and-time for the purpose.

 let now = date.format(new Date(), 'YYYYMMDD'); console.log(now); 
 <script src="https://cdn.jsdelivr.net/npm/date-and-time/date-and-time.min.js"></script> 

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