-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.

2

2 Answers 2

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/

Sign up to request clarification or add additional context in comments.

1 Comment

To show one digit minutes with 0 for example 9 as '09'
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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.