-2

HTML

<input type="datetime-local" onblur="window.setValue(this.value)" />

enter image description here

JS

window.setValue = function (val) {
    console.log(val);
}

The output above is 1991-03-02T00:01, how to get the exact value? Like 03/02/1991 12:01 AM.

Martin Tournoij
  • 26,737
  • 24
  • 105
  • 146
ivy ong
  • 101
  • 1
  • 6
  • possible duplicate of [Where can I find documentation on formatting a date in JavaScript](http://stackoverflow.com/questions/1056728/where-can-i-find-documentation-on-formatting-a-date-in-javascript) – ctwheels Jan 03 '15 at 02:19
  • Personally, I'm a huge fan of http://momentjs.com and http://momentjs.com/timezone/ – JAAulde Jan 03 '15 at 02:20

2 Answers2

0
function formatDate(date) {
  var hours = date.getHours();
  var minutes = date.getMinutes();
  var format = hours < 12 ? 'am' : 'pm';
  hours = hours % 12;
  hours = hours ? hours : 12; // making 0 a 12
  minutes = minutes < 10 ? '0'+minutes : minutes;
  var time = hours + ':' + minutes + ' ' + format;
  return date.getMonth()+1 + "/" + date.getDate() + "/" + date.getFullYear() + " " + time;
}

var date = new Date();
var output = formatDate(date);
alert(output);

Demo http://jsfiddle.net/64oyzhng/3/

chrana
  • 209
  • 1
  • 8
0

It is pretty easy to do using just javascript, as demonstrated by @chrana. There are also a number of libraries which use javascript's native Date object and allow formatting, moments.js is one of them. I have also been working on a library which will also allow formatting dates by using standard CLDR notation but does not rely on Date, instead everything is done in pure math, for accurate astronomy dating.

The format that you have shown is very similar to the standard US short date, except you have no ,

03/02/1991, 12:01 AM

But using my library and any library using CLDR notation it could be done like this.

MM/dd/Y h:mm a

require.config({
    paths: {
        'astrodate': '//rawgit.com/Xotic750/astrodate/master/lib/astrodate'
    }
});

require(['astrodate'], function (AstroDate) {
    "use strict";
    
    var date = new AstroDate('1991-03-02T00:01');

    document.body.appendChild(document.createTextNode(date.format('MM/dd/Y h:mm a')));
});
<script src="http://requirejs.org/docs/release/2.1.8/minified/require.js"></script>
Xotic750
  • 22,914
  • 8
  • 57
  • 79