Anil
Anil

Reputation: 3992

How to get the time converted to desired time zone

I have the following code

INPUT:

  var dateString =  "10/30/2014 02:15 PM +00:00";
  var a = dateString .split(/[^0-9]/);

  var dateVal=new Date(a[0],a[1]-1,a[2],a[3],a[4],a[5]);
  var minutes=dateVal.setMinutes(dateVal.getMinutes() + 330);
  var hours = dateVal.getHours(); 

     if(parseInt(hours,10) < 10){
        hours = "0"+hours;
     }
  var minutes = parseInt(dateVal.getMinutes());
  var ampm = parseInt(hours, 10) >= 12 ? 'PM' : 'AM';
  hours = parseInt(hours % 12);
  hours = hours ? hours : 12; // the hour '0' should be '12'
  minutes = minutes < 10 ? '0'+minutes : minutes;        
  strTime = hours + ':' + minutes + ' ' + ampm;
  return strTime

OUTPUT:

Actual: 7:45 AM
Expected : 7:45 PM

I am able to get the time zone converted but not able to get the desired output as i like to get 7:45 PM but i always get the way opposite. Can some help me out with this.

Upvotes: 1

Views: 34

Answers (1)

Markai
Markai

Reputation: 2098

The problem is, that a time past midday doesn't get detected, when you convert the string. Try to search for PM and if found increase your hours by twelve:

var dateString =  "10/30/2014 02:15 PM +00:00";
var a = dateString .split(/[^0-9]/);

if(dateString.indexOf("PM") != -1) a[3] = Number(a[3]) + 12;

var dateVal=new Date(a[0],a[1]-1,a[2],a[3],a[4],a[5]);

Upvotes: 1

Related Questions