0

Want to get Date output in 2 different formats. Here is what i have at the moment.

<p id="demo"></p>

<script>
var d = new Date(day, month);
document.getElementById("demo").innerHTML = d.toString();
</script>

Does not work for me.

With this code i want to get this output: 21 Jun

Also would like to know how to get date in this format:

Jun 21, 2016 12:00 AM

Roberts Šensters
  • 585
  • 1
  • 7
  • 23
  • 3
    Tip - look at `moment.js` - it does all this and whole lot more - parsing dates with javascript is not fun! – StudioTime Jun 21 '16 at 12:25

3 Answers3

0
var months = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
var h = d.getHours();
var ap = "AM";
if (h > 12) {
    h-=12;
    ap = "PM";
}
var dateString = months[d.getMonth()] + " " + d.getDate() + ", " + d.getFullYear() + " " + h + ":" + d.getMinutes() + " " + ap;
Mark Evaul
  • 653
  • 5
  • 11
  • If you are trying to format for your date parser on a server, I'd recommend using Ticks (d.getTime()) and converting that to a date on the server. It is much more specific and less prone to minor formatting errors. – Mark Evaul Jun 21 '16 at 12:31
0
var d = new Date();
var months = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
var h = d.getHours();
var ap = "AM";
if (h > 12) {
    h-=12;
    ap = "PM";
}
var dateString = months[d.getMonth()] + " " + d.getDate() + ", " + d.getFullYear() + " " + h + ":" + d.getMinutes() + " " + ap;
document.getElementById("demo").innerHTML = dateString.toString();

Try This one.

Tuks
  • 23
  • 6
0

JavaScript doesn't have functions to format the dates, so you'll have to do it manually. You can use this code for your first format:

<p id="demo"></p>

<script>
  var d = new Date(2016, 5, 21);
  document.getElementById("demo").innerHTML = getMonthName(d.getMonth()) + " " + d.getDate();

  function getMonthName(month) {
    var monthnames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
    return monthnames[month];
  }
</script>

You can add the code to do any other format you want. However, you'll quickly realize the reason why we have many libraries for that purpose. So, don't reinvent the wheel and just use one of those libraries.

Racil Hilan
  • 24,690
  • 13
  • 50
  • 55