Question

I have date in Wed Dec 11 00:00:00 EST 2013 this format. I want to convert this date into dd-mmm-yyyy format in JavaScript. How to convert it without changing timezone.

I had search for this solution and found below solution :

function getDateObject(dateString) {

    var dt = "";
    var ind = dateString.indexOf("EST");

    dt = dateString.substring(0, ind);
    dt += dateString.substring(ind+3, dateString.length);
    return new Date(dt);
}  
//convert this date into dd-mmm-yyyy format    
var now = getDateObject(MyDateString);
var frmDate = now.format('dd-mmm-yyyy');  

But i think this is not good solution, because if my date string timezone is change from EST to IST or any other timezone than it will not be worked.
Is there any good solution for convert date into required format ?
Thanks in advance.
Edit : If any one have solution using JQuery than it also good.

Was it helpful?

Solution

If your JSON date is in the format like Date(1396895400000)

then Convert your JSON date to string format as follow :

var dt = new Date(parseInt((/Date(1396895400000)/).substr(6))).toString();

Then dt will look like Tue Apr 08 2014 00:00:00 GMT+0530 (India Standard Time)

Now take substring from dt as follow:

dt.substr(8, 2) + "-" + (dt.substr(4, 3)) + "-" + dt.substr(11, 4)

Then your date will look like 08-Apr-2014

OTHER TIPS

If your date remains in the same format as Wed Dec 11 00:00:00 EST 2013 then take sub string from that date value.
In your case,If

var dt = 'Wed Dec 11 00:00:00 EST 2013';

then

dt.substr(8,2)+"-"+dt.substr(4,3)+"-"+dt.substr(24,4) 

will give you 11-Dec-2013.

Hi would recommend you use the following JS Library moment.js - http://momentjs.com/

    <!DOCTYPE html>
<html>
<!--
  Created using jsbin.com
  Source can be edited via http://jsbin.com/xicixeku/1/edit
-->
<head>
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/moment.js/2.7.0/moment.js"></script>  
  <meta charset="utf-8">
  <title>JS Bin</title>  

<style id="jsbin-css">

</style>
</head>
<body>



<script>
$(function()
  {
    var myDate = moment("Wed Dec 11 00:00:00 EST 2013");
    alert (myDate);        
    var newDate = moment(myDate).format('DD-MMM-YYYY');
    alert (newDate);
  });
</script>
</body>
</html>

I've created a JsBin with the example above so you can play around with it - hopefully this accomplishes exactly what you're looking for. This is the link

Edson

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top