Home jquery Date format in js

Date format in js

Author

Date

Category

I have a sample code:

$ ("# curday"). click (function () {
  var newdate;
  date = new Date ();
  newdate = date.getDate () + '.' + date.getMonth () + '.' + date.getFullYear ();
  $ ("# datepicker_down"). val (newdate);
});

But I have problems with him.

  1. The month starts with zero output, that is, I now have the 7th month, not the 8th, how can I correct this?
  2. The format for displaying the date is as follows: 07/20/2012, but I want to get this: 07/20/2012, that is, if the date and month have 1 digit, then a zero is automatically added in front of the machine.

Answer 1, authority 100%

I would advise you not to rack your brains, but to include the library datejs
Then you can write

$ ("# datepicker_down"). val ((new Date ()). toString ('dd.MM. yyyy '));

Answer 2, authority 98%

Since I’m lazy, collecting the date manually is a bummer)) Therefore, we include this script , then the format method is added to the prototype of the Data class, which performs date formatting in accordance with the passed template:

Date.prototype.format = function (mask, utc) {
  return dateFormat (this, mask, utc);
};

And now, we mock the date as you like:

var now = new Date ();
now.format ("m / dd / yy"); // 8/20/12
now.format ("dd.mm.yyyy"); // 08/20/2012
now.format ("dd mmm"); // 20 Aug
now.format ("ddd mmm dd yyyy HH: MM: ss"); // Mon Aug 20 2012 09:06:56
now.format ("h: MM: ss TT"); // 9:08:39 AM
// etc.

See example here

UPD: under the cut the code that is by the link


Answer 3, authority 98%

var options = {
year: 'numeric',
month: 'numeric',
day: 'numeric',
timezone: 'UTC'
};
alert (new Date (). toLocaleString ("ru", options));
// 07/20/2012 

Answer 4, authority 75%

Have you heard about the ternary operator?

var month = date.getMonth () + 1;
newdate = date.getDate () + '.'
     + (month & lt; 10? '0': '') + month + '.'
     + date.getFullYear ();

Answer 5

/ **
* Function of adding to date date several days specified in days
* @param date
* @param days
* @return string
* /
window.dateAdd = function (date, days) {
  var dateParsed = date.match (/ (\ d {1,2}) - (\ d {1,2}) - (\ d {2,4}) /);
  var date = new Date (dateParsed [3], dateParsed [2], dateParsed [1]);
  var day = date.getDate () + 1;
  var month = date.getMonth ();
  var year = date.getFullYear ();
  if (date & lt; 10) date = "0" + date;
  if (month & lt; 10) month = "0" + month;
  var newdateStr = day + '-' + month + '-' + year;
  return newdateStr;
}
Previous articleWhat does \ n mean?
Next articleSort array by value

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions