1

I want to convert UTC time to client browser time zone.

I am using below code

var utcDate = '08-Aug-17 10:12:29 AM' + ' UTC';
var date = new Date(utcDate);

Output: Tue Aug 08 2017 15:42:29 GMT+0530 (India Standard Time)

Expected output: 08-Aug-2017 3:42 PM

How can I format the date in javascript?

Rory McCrossan
  • 306,214
  • 37
  • 269
  • 303
ABB
  • 1,111
  • 1
  • 14
  • 30

3 Answers3

3

    function formatDate(date) {
      var monthNames = [
        "Jan", "Feb", "Mar",
        "Apr", "May", "Jun", "Jul",
        "Aug", "Sep", "Oct",
        "Novr", "Dec"
      ];

      var day = date.getDate();
      var monthIndex = date.getMonth();
      var year = date.getFullYear();
      var tim =  date.getHours() + ":"  
                               +date.getMinutes();
     function tConvert (time) {
     time = time.toString ().match (/^([01]\d|2[0-3])(:)([0-5]\d)(:[0-5]\d)?$/) 
    if (time.length > 1) 
     { 
      time = time.slice (1);  
      time[5] = +time[0] < 12 ? 'AM' : 'PM'; 
      time[0] = +time[0] % 12 || 12;
     }
  return time.join (''); // return adjusted time or original string
}
  return day + ' ' + monthNames[monthIndex] + ' ' + year +' '+tConvert (tim); ;
    }

    console.log(formatDate(new Date()));  // show current date-time in console
Nithin
  • 1,270
  • 10
  • 28
1

for this, you have to use momentJS
using momentJS you can do it by following way

var utcDate = '08-Aug-17 10:12:29 AM' + ' UTC';
console.log(moment(utcDate).format('DD-MMM-YYYY hh:mm:ss a')); 
Pranav Patel
  • 1,792
  • 10
  • 25
0

You can use moment library to lot of date time related issues arise in your applications.

moment.utc('Your UTC time here').locale("your culture here").format('llll')

Download momentJs here

SilentCoder
  • 1,890
  • 1
  • 14
  • 21