Advertisement
Advertisement


jQuery date formatting


Question

How can I format the date using jQuery. I am using below code but getting error:

 $("#txtDate").val($.format.date(new Date(), 'dd M yy'));

Please suggest a solution.

2014/08/29
1
187
8/29/2014 12:43:41 PM

Accepted Answer

jQuery dateFormat is a separate plugin. You need to load that explicitly using a <script> tag.

2013/12/23
104
12/23/2013 12:31:00 AM


An alternative would be simple js date() function, if you don't want to use jQuery/jQuery plugin:

e.g.:

var formattedDate = new Date("yourUnformattedOriginalDate");
var d = formattedDate.getDate();
var m =  formattedDate.getMonth();
m += 1;  // JavaScript months are 0-11
var y = formattedDate.getFullYear();

$("#txtDate").val(d + "." + m + "." + y);

see: 10 ways to format time and date using JavaScript

If you want to add leading zeros to day/month, this is a perfect example: Javascript add leading zeroes to date

and if you want to add time with leading zeros try this: getMinutes() 0-9 - how to with two numbers?

2017/05/23

Here's a really basic function I just made that doesn't require any external plugins:

$.date = function(dateObject) {
    var d = new Date(dateObject);
    var day = d.getDate();
    var month = d.getMonth() + 1;
    var year = d.getFullYear();
    if (day < 10) {
        day = "0" + day;
    }
    if (month < 10) {
        month = "0" + month;
    }
    var date = day + "/" + month + "/" + year;

    return date;
};

Use:

$.date(yourDateObject);

Result:

dd/mm/yyyy
2017/07/31

ThulasiRam, I prefer your suggestion. It works well for me in a slightly different syntax/context:

var dt_to = $.datepicker.formatDate('yy-mm-dd', new Date());

If you decide to utilize datepicker from JQuery UI, make sure you use proper references in your document's < head > section:

<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" />

<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script> 
2015/01/30

I'm using Moment JS. Is very helpful and easy to use.

var date = moment(); //Get the current date
date.format("YYYY-MM-DD"); //2014-07-10
2014/07/10

I hope this code will fix your problem.

var d = new Date();

var curr_day = d.getDate();
var curr_month = d.getMonth();
var curr_year = d.getFullYear();

var curr_hour = d.getHours();
var curr_min = d.getMinutes();
var curr_sec = d.getSeconds();

curr_month++ ; // In js, first month is 0, not 1
year_2d = curr_year.toString().substring(2, 4)

$("#txtDate").val(curr_day + " " + curr_month + " " + year_2d)
2014/09/14

Source: https://stackoverflow.com/questions/5250244
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]