jQuery date formatting
Asked Answered
H

24

202

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.

Hagan answered 9/3, 2011 at 18:11 Comment(9)
Microsoft JScript runtime error: '$.format' is null or not an objectHagan
have you included the plugin that includes the format functions?Witching
Sneaky one liner for yyyy-mm-dd: new Date().toJSON().substring(0,10)Damp
it's fformat (double f)Fennel
Mike Causer, you're a genius!Theresiatheresina
Mike Causer, brilliant. If you want time as well then you can do this: new Date().toJSON().substring(0,19).replace('T',' ');Mythicize
WARNING! the slick code: new Date().toJSON().substring(0,10) worked nice, but it returns date as GMT! Since we are 7 hours behind GMT, I was getting the wrong date after 5:00pm. I just wasted a couple hours finding the cause /sigh/. ReferenceUlland
Mike Causer you rock. new Date().toISOString().substring(0,10)Invagination
@JayRO-GreyBeard, one liner with timezoneOffset: new Date().toLocaleDateString();. Converts the date portion of a Date object into a readable stringTavern
G
112

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

Garlicky answered 9/3, 2011 at 18:17 Comment(8)
@Dotnet sure, using other functions: See e.g. hereGarlicky
I dont want to use plugin. CAn you please tell me how can I format the date ?Hagan
@Dotnet see the link in my commentGarlicky
@Dotnet if it could be done using jQuery, there would not be a jQuery plug-in for date formatting, would there?Garlicky
I can't tell if this should be a joke or not... it's almost brilliant @pekka. Also, it's the right answer.Chrysostom
jQuery dateFormat doesn't works with jQuery Validate. Neither the pure JavaScript version.Y
It is hard to believe that vanilla jQuery doesn't have a function to format a date. This question is 5 years old, is this still the case?Gerome
@Gerome a cursory Google search suggests that indeed is the case! Perhaps they felt it's functionality they want to keep out of the core library for bandwidth and performance reasons.Garlicky
E
223

add jquery ui plugin in your page.

 $("#txtDate").val($.datepicker.formatDate('dd M yy', new Date()));
Ellie answered 29/6, 2012 at 11:51 Comment(6)
This is the answer I was looking for, especially since I am using jQuery UI elsewhere.Mown
Is there any way to get date + 2 years ?Feed
var currentDate = new Date(); currentDate.setFullYear(currentDate.getFullYear() + 2);Ellie
it is a pitty that it doesnt support time formatting =SLungwort
Here's the link to the official doc : api.jqueryui.com/datepicker/#utility-formatDateGarrik
what a strange library. 'dd M yy' is understood as 'dd MMM yyyy'. This library has it's own understanding of formatSchiff
G
112

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

Garlicky answered 9/3, 2011 at 18:17 Comment(8)
@Dotnet sure, using other functions: See e.g. hereGarlicky
I dont want to use plugin. CAn you please tell me how can I format the date ?Hagan
@Dotnet see the link in my commentGarlicky
@Dotnet if it could be done using jQuery, there would not be a jQuery plug-in for date formatting, would there?Garlicky
I can't tell if this should be a joke or not... it's almost brilliant @pekka. Also, it's the right answer.Chrysostom
jQuery dateFormat doesn't works with jQuery Validate. Neither the pure JavaScript version.Y
It is hard to believe that vanilla jQuery doesn't have a function to format a date. This question is 5 years old, is this still the case?Gerome
@Gerome a cursory Google search suggests that indeed is the case! Perhaps they felt it's functionality they want to keep out of the core library for bandwidth and performance reasons.Garlicky
V
109

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?

V1 answered 25/4, 2013 at 10:3 Comment(2)
it will be handy to add seconds as @sein didSelfdeprecating
This is good until the user wants the recent date or a date is fed into the Date object. What about getting the date in the same format but 6 months prior to the fed date ??Wotan
S
40

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
Sewellel answered 6/6, 2013 at 9:8 Comment(2)
thanks super cool easy to use I tried working perfectlyGrabowski
superb SolutionVodka
A
32

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
Aeneous answered 10/7, 2014 at 4:56 Comment(0)
T
29

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> 
Thames answered 30/12, 2012 at 0:55 Comment(0)
H
17

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)
Higgs answered 14/9, 2014 at 16:0 Comment(0)
A
10

Add this function to your <script></script> and call from where ever you want in that <script></script>

<script>

function GetNow(){
    var currentdate = new Date(); 
    var datetime = currentdate.getDate() + "-"
            + (currentdate.getMonth()+1)  + "-" 
            + currentdate.getFullYear() + " "  
            + currentdate.getHours() + ":"  
            + currentdate.getMinutes() + ":" 
            + currentdate.getSeconds();
    return datetime;
}

window.alert(GetNow());

</script>

or you may simply use the Jquery which provides formatting facilities also:-

window.alert(Date.parse(new Date()).toString('yyyy-MM-dd H:i:s'));

I love the second option. It resolves all issues in one go.

Americanist answered 9/3, 2011 at 18:12 Comment(2)
That 2nd option gives me "radix argument must be between 2 and 36 at Number.toString". It crashes.Kaykaya
We can't use second option as it will throw errorEskil
K
9

If you are using jquery ui then you may use it like below, you can specify your own date format

$.datepicker.formatDate( "D dd-M-yy", new Date()) // Output "Fri 08-Sep-2017"
Koala answered 8/9, 2017 at 8:1 Comment(0)
K
8

Just use this:

var date_str=('0'+date.getDate()).substr(-2,2)+' '+('0'+date.getMonth()).substr(-2,2)+' '+('0'+date.getFullYear()).substr(-2,2);
Kaslik answered 22/4, 2012 at 22:7 Comment(1)
Note, this gives you a date one month in the past (unless it's accessed in January in which case it gives you '00' for the month) because date.getMonth() is a zero-based index.Afghan
W
6

Though this question was asked a few years ago, a jQuery plugin isn't required anymore provided the date value in question is a string with format mm/dd/yyyy (like when using a date-picker);

var birthdateVal = $('#birthdate').val();
//birthdateVal: 11/8/2014

var birthdate = new Date(birthdateVal);
//birthdate: Sat Nov 08 2014 00:00:00 GMT-0500 (Eastern Standard Time)
Wobble answered 30/1, 2015 at 15:6 Comment(0)
T
6

You can add new user jQuery function 'getDate'

JSFiddle: getDate jQuery

Or you can run code snippet. Just press "Run code snippet" button below this post.

// Create user jQuery function 'getDate'
(function( $ ){
   $.fn.getDate = function(format) {

	var gDate		= new Date();
	var mDate		= {
	'S': gDate.getSeconds(),
	'M': gDate.getMinutes(),
	'H': gDate.getHours(),
	'd': gDate.getDate(),
	'm': gDate.getMonth() + 1,
	'y': gDate.getFullYear(),
	}

	// Apply format and add leading zeroes
	return format.replace(/([SMHdmy])/g, function(key){return (mDate[key] < 10 ? '0' : '') + mDate[key];});

	return getDate(str);
   }; 
})( jQuery );


// Usage: example #1. Write to '#date' div
$('#date').html($().getDate("y-m-d H:M:S"));

// Usage: ex2. Simple clock. Write to '#clock' div
function clock(){
	$('#clock').html($().getDate("H:M:S, m/d/y"))
}
clock();
setInterval(clock, 1000); // One second

// Usage: ex3. Simple clock 2. Write to '#clock2' div
function clock2(){

	var format = 'H:M:S'; // Date format
	var updateInterval = 1000; // 1 second
	var clock2Div	= $('#clock2'); // Get div
	var currentTime	= $().getDate(format); // Get time
	
	clock2Div.html(currentTime); // Write to div
	setTimeout(clock2, updateInterval); // Set timer 1 second
	
}
// Run clock2
clock2();

// Just for fun
// Usage: ex4. Simple clock 3. Write to '#clock3' span

function clock3(){

	var formatHM = 'H:M:'; // Hours, minutes
	var formatS = 'S'; // Seconds
	var updateInterval = 1000; // 1 second
	var clock3SpanHM	= $('#clock3HM'); // Get span HM
	var clock3SpanS	= $('#clock3S'); // Get span S
	var currentHM	= $().getDate(formatHM); // Get time H:M
	var currentS	= $().getDate(formatS); // Get seconds
	
	clock3SpanHM.html(currentHM); // Write to div
	clock3SpanS.fadeOut(1000).html(currentS).fadeIn(1); // Write to span
	setTimeout(clock3, updateInterval); // Set timer 1 second
	
}
// Run clock2
clock3();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>

<div id="date"></div><br>
<div id="clock"></div><br>
<span id="clock3HM"></span><span id="clock3S"></span>

Enjoy!

Tavern answered 16/9, 2016 at 23:31 Comment(0)
M
5

You could make use of this snippet

$('.datepicker').datepicker({
  changeMonth: true,
  changeYear: true,
  yearRange: '1900:+0',
  defaultDate: '01 JAN 1900',
  buttonImage: "http://www.theplazaclub.com/club/images/calendar/outlook_calendar.gif",
  dateFormat: 'dd/mm/yy',
  onSelect: function() {
    $('#datepicker').val($(this).datepicker({
      dateFormat: 'dd/mm/yy'
    }).val());
  }
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>

<p>
  selector: <input type="text" class="datepicker">
</p>
<p>
  output: <input type="text" id="datepicker">
</p>
Mordy answered 15/4, 2015 at 4:4 Comment(0)
C
5

Simply we can format the date like,

var month = date.getMonth() + 1;
var day = date.getDate();
var date1 = (('' + day).length < 2 ? '0' : '') + day + '/' + (('' + month).length < 2 ? '0' : '') + month + '/' + date.getFullYear();
$("#txtDate").val($.datepicker.formatDate('dd/mm/yy', new Date(date1)));

Where "date" is a date in any format.

Corded answered 18/1, 2016 at 11:19 Comment(0)
E
4

Take a look here:

https://github.com/mbitto/jquery.i18Now

This jQuery plugin helps you to format and translate date and time according to your preference.

Enchanting answered 11/6, 2012 at 7:31 Comment(0)
T
2

Use dateFormat option when creating date picker.

$("#startDate").datepicker({
                    changeMonth: true,
                    changeYear: true,
                    showButtonPanel: true,
                    dateFormat: 'yy/mm/dd'
                });
Teuton answered 25/11, 2014 at 5:3 Comment(0)
T
2

you can use the below code without the plugin.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script>
$( function() {
    //call the function on page load
	$( "#datepicker" ).datepicker();
    //set the date format here
    $( "#datepicker" ).datepicker("option" , "dateFormat", "dd-mm-yy");
	
    // you also can use 
    // yy-mm-dd
    // d M, y
    // d MM, y
    // DD, d MM, yy
    // &apos;day&apos; d &apos;of&apos; MM &apos;in the year&apos; yy (With text - 'day' d 'of' MM 'in the year' yy)
	} );
 </script>

Pick the Date: <input type="text" id="datepicker">
Tobit answered 1/6, 2017 at 7:32 Comment(0)
A
2

You can try http://www.datejs.com/

 $('#idInput').val( Date.parse("Jun 18, 2017 7:00:00 PM").toString('yyyy-MM-dd'));

BR

Arouse answered 17/6, 2017 at 17:24 Comment(0)
R
2

This worked for me with slight modification and without any plugin

Input : Wed Apr 11 2018 00:00:00 GMT+0000

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

$.date('Wed Apr 11 2018 00:00:00 GMT+0000')

Output: 04/11/2018

Resurgent answered 4/4, 2018 at 6:41 Comment(0)
E
2

I have achieved through this, I have resolved this without any plugin or datepicker.

GetDatePattern("MM/dd/yyyy");
 function GetDatePattern(pattern)
    {
    var monthNames=["January", "February", "March", "April", "May", "June",
                "July", "August", "September", "October", "November", "December"];
    
            var todayDate = new Date();
                                              
                            var date = todayDate.getDate().toString();
                            var month = todayDate.getMonth().toString(); 
                            var year = todayDate.getFullYear().toString(); 
                            var formattedMonth = (todayDate.getMonth() < 10) ? "0" + month : month;
                            var formattedDay = (todayDate.getDate() < 10) ? "0" + date : date;
                            var result = "";
    
                            switch (pattern) {
                                case "M/d/yyyy": 
                                    formattedMonth = formattedMonth.indexOf("0") == 0 ? formattedMonth.substring(1, 2) : formattedMonth;
                                    formattedDay = formattedDay.indexOf("0") == 0 ? formattedDay.substring(1, 2) : formattedDay;
    
                                    result  = formattedMonth + '/' + formattedDay + '/' + year;
                                    break;
    
                                case "M/d/yy": 
                                    formattedMonth = formattedMonth.indexOf("0") == 0 ? formattedMonth.substring(1, 2) : formattedMonth;
                                    formattedDay = formattedDay.indexOf("0") == 0 ? formattedDay.substring(1, 2) : formattedDay;
                                    result  = formattedMonth + '/' + formattedDay + '/' + year.substr(2);
                                    break;
    
                                case "MM/dd/yy":
                                    result  = formattedMonth + '/' + formattedDay + '/' + year.substr(2);
                                    break;
    
                                case "MM/dd/yyyy":
                                   result  = formattedMonth + '/' + formattedDay + '/' + year;
                                    break;
    
                                case "yy/MM/dd":
                                    result  = year.substr(2) + '/' + formattedMonth + '/' + formattedDay;
                                    break;
    
    
                                case "yyyy-MM-dd":
                                    result  = year + '-' + formattedMonth + '-' + formattedDay;
                                    break;
    
                                case "dd-MMM-yy":
                                   result  = formattedDay + '-' + monthNames[todayDate.getMonth()].substr(3) + '-' + year.substr(2);
                                    break;
    
                                case "MMMM d, yyyy":
                                    result  = todayDate.toLocaleDateString("en-us", { day: 'numeric', month: 'long', year: 'numeric' });
                                    break;
    
    
                            }
                            }
Eskil answered 23/3, 2021 at 11:37 Comment(0)
D
1

I'm not quite sure if I'm allowed to answer a question that was asked like 2 years ago as this is my first answer on stackoverflow but, here's my solution;

If you once retrieved the date from your MySQL database, split it and then use the splitted values.

$(document).ready(function () {
    var datefrommysql = $('.date-from-mysql').attr("date");
    var arraydate = datefrommysql.split('.');
    var yearfirstdigit = arraydate[2][2];
    var yearlastdigit = arraydate[2][3];
    var day = arraydate[0];
    var month = arraydate[1];
    $('.formatted-date').text(day + "/" + month + "/" + yearfirstdigit + yearlastdigit);
});

Here's a fiddle.

Disjunct answered 11/4, 2014 at 1:32 Comment(0)
S
1

Here is the full code example I have show on browser, Hope you also helpful thanks.

<!doctype html>
<html lang="en">
   <head>
      <meta charset="utf-8">
      <title>jQuery UI Datepicker functionality</title>
      <link href="http://code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css" rel="stylesheet">
      <script src="http://code.jquery.com/jquery-1.10.2.js"></script>
      <script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
      <!-- Javascript -->
      <script>
         $(function() {
            $( "#datepicker" ).datepicker({
                minDate: -100,
                maxDate: "+0D",
                dateFormat: 'yy-dd-mm',
                onSelect: function(datetext){
                    $(this).val(datetext);
                },
            });
         });
      </script>
   </head>
   <body>
      <!-- HTML --> 
      <p>Enter Date: <input type="text" id="datepicker"></p>
   </body>
</html>
Sammysamoan answered 3/3, 2015 at 11:0 Comment(0)
L
0

using Moment JS moment js

$("#YourDateInput").val(moment($("#YourDateInput").val()).format('YYYY-MM-DD'));
Lili answered 23/6, 2022 at 22:5 Comment(0)
A
-1

u can use this coding

$('[name="tgllahir"]').val($.datepicker.formatDate('dd-mm-yy', new Date(data.tgllahir)));
Acropetal answered 23/9, 2017 at 15:28 Comment(2)
Code-only answers are discouraged because they do not explain how they resolve the issue. Please update your answer to explain how this improves on the many other accepted and upvoted answers this question already has. Also, this question is 6 years old, your efforts would be more appreciated by users who have recent unanswered questions. Please review How do I write a good answer.Macomber
Answer didn't mention jQuery UI was requiredHeuer

© 2022 - 2024 — McMap. All rights reserved.