3

I have a date in the format 14-Feb-2011, but I want to convert it into the format Mon Feb 14 10:13:50 UTC+0530 2011. How Can I achieve this?

Rob
  • 45,296
  • 24
  • 122
  • 150
Akshay
  • 119
  • 2
  • 2
  • 4
  • Are you utilizing a javascript library or is this vanilla javascript? – erlando Feb 14 '11 at 09:13
  • I think this will be helpful [How can I convert string to datetime with format specification in JavaScript?](http://stackoverflow.com/questions/476105/how-can-i-convert-string-to-datetime-with-format-specification-in-javascript) – Marat Faskhiev Feb 14 '11 at 09:18

2 Answers2

3

Using new Date(Date.UTC(year, month, day, hour, minute, second)) you can create a Date-object from a specific UTC time.

I tried this code and it returned proper date (In Indian Locale)

var d=Date.parse("14,Feb,2011");
document.write(new Date(d));

Output:

Mon Feb 14 2011 00:00:00 GMT+0530 (India Standard Time) .


Here's an example of converting between different time zones.
<html>
<body>

<script type="text/javascript">

//Set you offset here like +5.5 for IST
var offsetIST = 5.5;


//Set you offset here like -8 for PST
var offsetPST = -8;

//Create a new date from the Given string
var d=new Date(Date.parse("14,Feb,2011"));

//To convert to UTC datetime by subtracting the current Timezone offset
var utcdate =  new Date(d.getTime() + (d.getTimezoneOffset()*60000));

//Then cinver the UTS date to the required time zone offset like back to 5.5 for IST
var istdate =  new Date(utcdate.getTime() - ((-offsetIST*60)*60000));

//Then cinver the UTS date to the required time zone offset like back to -8 for PST (Canada US)
var pstdate=  new Date(utcdate.getTime() - ((-offsetPST*60)*60000));

document.write(d);
document.write("<br/>");
document.write(utcdate);
document.write("<br/>");
document.write(istdate);
document.write("<br/>");
document.write(pstdate);
</script>

</body>
</html>

Output:

Mon Feb 14 2011 00:00:00 GMT+0530 (India Standard Time)
Sun Feb 13 2011 18:30:00 GMT+0530 (India Standard Time)
Mon Feb 14 2011 00:00:00 GMT+0530 (India Standard Time)
Sun Feb 13 2011 10:30:00 GMT+0530 (India Standard Time) 

Its writing IST every where because new Date() always show date as local timezone (which is IST for me) but above datetime are actually Original, UTC, IST, PST respectively.

Shekhar_Pro
  • 18,056
  • 9
  • 55
  • 79
0
var d = new Date("14-Feb-2011");

this will give an output of Mon Feb 14 2011 00:00:00 GMT-0500 (Eastern Standard Time)

Ganesh
  • 1,654
  • 2
  • 19
  • 32