Formatting Date Value In Javascript
HTML JS window.setValue = function (val) { console.log(val); } The output above is 1991-03-02T00:
Solution 1:
functionformatDate(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;
returndate.getMonth()+1 + "/" + date.getDate() + "/" + date.getFullYear() + " " + time;
}
var date = new Date();
var output = formatDate(date);
alert(output);
Solution 2:
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/Yh:mma
require.config({
paths: {
'astrodate': '//rawgit.com/Xotic750/astrodate/master/lib/astrodate'
}
});
require(['astrodate'], function (AstroDate) {
"use strict";
var date = newAstroDate('1991-03-02T00:01');
document.body.appendChild(document.createTextNode(date.format('MM/dd/Y h:mm a')));
});
<scriptsrc="http://requirejs.org/docs/release/2.1.8/minified/require.js"></script>
Post a Comment for "Formatting Date Value In Javascript"