1

How can I format a JavaScript date time relative to UTC format.

For (eg): '2015-03-25T12:00:00-06:30' my UTC time format. How can i change this to mm/dd/yyyy at hh:mm meridiem

Manush
  • 1,852
  • 7
  • 26
  • 39

2 Answers2

0

You use Date methods in Javascrpit:

var d = new Date();
var year = d.getFullYear();
var month = d.getMonth();
var day = d.getDate();
var hour = d.getHours();
var min = d.getMinutes() ;
melhirech
  • 49
  • 8
0

you can use like that.

function getLocalizeDateTime(dateString,format) {
 if(dateString==null || dateString==undefined || dateString==""){
  return "";
 }
   var dateTime = dateString.trim().split(" ");
    var dateOnly = dateTime[0];
    var timeOnly = dateTime[1];
    timeOnlyOfDate = timeOnly;
    var temp = dateOnly + "T" + timeOnly+"Z";
    var utc_date =new Date(temp);
    currentDateStr = dateString;
   
  //var offset = new Date().getTimezoneOffset();
  //utc_date.setMinutes(utc_date.getMinutes() - offset);
  if(format!=undefined && format!=null)
   return date2str(utc_date,format);
  return date.toString();
}

function date2str(x, y) {
    var z = {
        M: x.getMonth() + 1,
        d: x.getDate(),
        h: x.getHours(),
        m: x.getMinutes(),
        s: x.getSeconds()
    };
    y = y.replace(/(M+|d+|h+|m+|s+)/g, function(v) {
        return ((v.length > 1 ? "0" : "") + eval('z.' + v.slice(-1))).slice(-2)
    });

    return y.replace(/(y+)/g, function(v) {
        return x.getFullYear().toString().slice(-v.length)
    });
}

console.log(getLocalizeDateTime('2017-05-12 13:07:22.246','MM/dd/yyyy'))
manikant gautam
  • 3,521
  • 1
  • 17
  • 27
  • Why have you included jQuery in the snippet when there is no jQuery in the answer? Also there is gratuitous use of *eval* and it doesn't format the time per the OP. – RobG May 13 '17 at 23:18
  • RobG is it really necessary to do down vote each time ? I would have removed by your comment itself. – manikant gautam May 13 '17 at 23:24
  • You removed jQuery, but your input format is different to the OP, so the function does't work with the OP format. The other issues remain (but this is a duplicate anyway). – RobG May 13 '17 at 23:55
  • RobG it still works – manikant gautam May 13 '17 at 23:59