简体   繁体   中英

Convert UTC Date to dd/mm/yyyy Format

I am having some difficulties when trying to convert UTC Date format to dd/mm/yyyy in JavaScript:

var launchDate = attributes["launch_date"];
if (isBuffering) {
         var date = new Date(launchDate);
         var d = new Date(date.toLocaleDateString());
         launchDate = ((d.getUTCMonth() + 1) + "/" + (d.getUTCDate() + 1) + "/" + (d.getUTCFullYear()));
 } 

I tried with this, but it returns me an invalid date. So I changed to this:

var launchDate = attributes["launch_date"];
if (isBuffering) {
         var date = new Date(launchDate);
         var d = formatDate(new Date(date.toLocaleDateString()));
         launchDate = ((d.getUTCMonth() + 1) + "/" + (d.getUTCDate() + 1) + "/" + (d.getUTCFullYear()));
 }

However, it still returning me invalid Date. I wonder is there any possible way to change the date format of Fri May 31 2013 17:41:01 GMT+0200 (CEST) to dd/mm/yyyy?

Thanks in advance.

var d = new Date();
var n = d.toLocaleDateString();

This will be more superior in build JS method!

function formatDate(d)
 {
  date = new Date(d)
  var dd = date.getDate(); 
  var mm = date.getMonth()+1;
  var yyyy = date.getFullYear(); 
  if(dd<10){dd='0'+dd} 
  if(mm<10){mm='0'+mm};
  return d = dd+'/'+mm+'/'+yyyy
}

Month is 0 indexed, but day is not. You don't need to add 1 to your day.

Also, you're formatting it for MM/dd/yyyy, not dd/MM/yyyy.

solution:

    var launchDate = attributes["launch_date"];
    if (isBuffering) {
             var date = new Date(launchDate);
             var d = formatDate(new Date(date.toLocaleDateString()));
             launchDate = ((d.getUTCDate())+ "/" + (d.getUTCMonth() + 1) +  "/" + (d.getUTCFullYear()));
     }

Try it:

Date.parseExact(Your_Date, 'dd/MM/yyyy').toString('MM/dd/yyyy');

or

Date.parseExact(Your_Date, 'MM/dd/yyyy').toString('dd/MM/yyyy');

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