Reputation: 3560
I am trying to format date time using JavaScript/jQuery but it's not happening. My code is below.
<div id="divID"></div>
<script>
var formatDate = function(date){
return date.getDate() + "/" + date.getMonth() + "/" +date.getYear() + " "+ date.getHours() + ":" + date.getMinutes() + ":" + date.getMintutes() + ":" + date.getSeconds();
}
var timestamp="2016-12-16 07:58:30 AM ";
var date= new Date(timestamp);
document.getElementById('divID').innerHTML = formatDate(date);
</script>
Here I have the existing time 2016-12-16 07:58:30 AM
and I need change it to 16-12-2016 07:58:30 AM
but here I could not get the proper output.
Upvotes: 1
Views: 23197
Reputation: 630
You can get the desired output using JQuery UI Datepicker Widget as shown below.
var timestamp="2016-12-16 07:58:30 AM ";
var desiredTimestamp = $.datepicker.formatDate('dd-mm-yy', new Date(timestamp.split(' ')[0])) + ' ' + timestamp.split(' ')[1] + ' ' + timestamp.split(' ')[2];
Upvotes: 0
Reputation: 630
You can use JQuery UI Datepicker for getting the formatted date like the following.
let myDate = '2020-11-10';
$.datepicker.formatDate('dd-M-yy', new Date(myDate));
The above code will return 10-Nov-2020.
Upvotes: 0
Reputation: 3294
jQuery dateFormat is a separate plugin. You need to load that explicitly using a <script>
tag.
Upvotes: 0
Reputation: 11482
The timestamp you are using will return an invalid date so you should remove the AM
. Using moment.js you can do it like this:
var timestamp = "2016-12-16 07:58:30";
var formattedDate = moment(timestamp).format('DD-MM-YYYY h:mm:ss A');
console.log(formattedDate);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.5.1/moment.min.js"></script>
Upvotes: 2
Reputation: 337580
Your code has a few issues:
getMintutes()
getFullYear()
fits your needs better than getYear()
-
not /
to delimit the date values. AM
or PM
to the end of the string by checking if hours < 12
With that in mind, try this:
var formatDate = function(date) {
return date.getDate() + "-" + date.getMonth() + "-" + date.getFullYear() + " " + ('0' + date.getHours()).slice(-2) + ":" + ('0' + date.getMinutes()).slice(-2) + ":" + ('0' + date.getSeconds()).slice(-2) + ' ' + (date.getHours() < 12 ? 'AM' : 'PM');
}
var timestamp = "2016-12-16 07:58:30";
var date = new Date(timestamp);
document.getElementById('divID').innerHTML = formatDate(date);
<div id="divID"></div>
You could use a library to make the date formatting logic simpler, but it's rather wasteful to load an entirely library when a single line of code works fine.
Upvotes: 5
Reputation: 4000
you can use a library named moment.js
http://momentjs.com/
var date = new Date();
moment(date).format('DD-MM-YYYY HH:mm:ss A')
Upvotes: 1