0

I have a function which accepts a UTC date. I want to return back the local date. I have the following code so far:

    var dateFormat = function (date) {
        var dt = new Date(date + " UTC");
        return dt.toString(); 
       }

For the return date, I like it formatted as such:

     October 9th, 2013, 7:34:00 PM

Is there a formatting that will handle this.

Silviu Burcea
  • 5,103
  • 1
  • 29
  • 43
Nate Pet
  • 44,246
  • 124
  • 269
  • 414

2 Answers2

0

You have a lot of ways to format the Date object in JavaScript. I suggest you to check out 10 ways to format time and date using JavaScript and Working with Dates. These are the main functions you need to use for formatting JavaScript Dates:

getDate(): Returns the date
getMonth(): Returns the month (Starting from 0)
getFullYear(): Returns the year

A simple script would be:

<script type="text/javascript">
    var d = new Date();
    var curDate = d.getDate();
    var curMonth = d.getMonth() + 1; // Months are zero based
    var curYear = d.getFullYear();
    document.write(curDate + "-" + curMonth + "-" + curYear);
</script>

In your case, you can have an array of months:

var months = ["January", "February", ... "December"];

The next part would be associating the correct variables with the place they need to be present.

Plugins

But instead of doing all these, you can also consider using a fancy date formatter plugin, that uses jQuery or some library. A few ones would be:

  1. Moment.js is a javascript date library for parsing, validating, manipulating, and formatting dates.
  2. XDate is a thin wrapper around JavaScript's native Date object that provides enhanced functionality for parsing, formatting, and manipulating dates. It implements the same methods as the native Date, so it should seem very familiar.
  3. DateJS is an open source JavaScript Date library for parsing, formatting and processing.
Community
  • 1
  • 1
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
0

I usually use moment.js for this kind of tasks. It's pretty powerful and still small sized library. Give it a try.

Silviu Burcea
  • 5,103
  • 1
  • 29
  • 43