1

I have a list of items that I am displaying on a screen. The HTML template for each item looks like this:

<div>
  [Comments]
</div>
<small>Posted on: [date]</small>

[Comments] will be an actual string of text entered by a user. While [date] is a JavaScript Date object. I want to display [date] in a localized date format with the month, day, and year. How can I do this using as plain as possible JavaScript?

Thank you!

JQuery Mobile
  • 6,221
  • 24
  • 81
  • 134
  • `Posted on` seems to be a date coming from the serverside pertaining to stored comments, are you sure it wouldn't be better to be consisitent and output the dates on the serverside, instead of relying on the users clientside date and time settings ? – adeneo Mar 17 '15 at 13:24

4 Answers4

2

There's always moment.js for a little bit more flexibility with your presentation and localisation.

Chris
  • 44,602
  • 16
  • 137
  • 156
OliverJ90
  • 1,291
  • 2
  • 21
  • 42
0

Use some thirdy-part library that already does this.

It has been discussed before: internationalization of dates on the web How does internationalization work in JavaScript?

Community
  • 1
  • 1
Christian Benseler
  • 7,907
  • 8
  • 40
  • 71
0

you may use this code...

<script>
var d = new Date();
document.getElementById("demo").innerHTML = d.toUTCString();
</script>
Choxx
  • 945
  • 1
  • 24
  • 46
-1

Use the Date method toLocaleFormat(formatString)

var today = new Date();
today.toLocaleFormat('%d-%b-%Y'); // 30-Dec-2011
Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109
  • -1 From [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleFormat): "This … is non-standard and is not on a standards track. **Do not use it on production sites facing the Web: it will not work for every user**. There may also be large incompatibilities between implementations and the behavior may change in the future." This should not be the recommend answer. Use a library like [moment.js](http://www.momentjs.com/) or wait until [ECMAScript Internationalization API Specification](http://ecma-international.org/ecma-402/1.0/) is widely supported. – Chris Mar 19 '15 at 13:27