Javascript getdate с нулями

getDate

а как сделать, чтобы возвращало, например, не 1, а 01 .

function check(i) var i;
if (i <10) ;
i = «0»+i;
return i;

var sputnikLaunch = new Date(«October 4, 1957 19:28:34 GMT»)

// Жители Дальнего Востока получат здесь 5
day = sputnikLaunch.getDate();

var zeros = ['00', '0', '']; var dayString = new String(dateObject.getDate()); return zeros[dayString.length] + dayString;

Что-то вы, ребята, усложняете:

var sputnikLaunch = new Date("October 4, 1957 19:28:34 GMT"); var day = ('0'+sputnikLaunch.getDate()).slice(-2); alert('Day: ' + day); var someDate = new Date("March 22, 1966 11:11:11 GMT"); var someDay = ('0'+someDate.getDate()).slice(-2); alert('Some day: ' + someDay);

В данном случае к строке с днём добавляется предстоящий ноль, а методом slice берутся два последних символа, что позволяет избавится от проверок длины.

Аналогично можно форматировать и месяц, например.

Ну не знаю. меня только так устраивает:

var D,d; D=new Date(); d=D.getDate(); d=d>9?d:'0'+d; // метод 1 if(d<10)d='0'+d; // метод 2 // метод 3 (сокращённый метод из предыдущего комментария): var Z = ['','0']; d=''+d; d=Z[d.length]+d;

да и, как известно, чем короче интерпретируемый код, тем быстрее он выполняется. но лично меня не скорость интересует.. а читабельность и понятность. чем код короче, тем легче глазу он воспринимается.

код не сработает, ибо D и d в яваскрипт совпадает =)
просто переименовать D в DT например )

JavaScript чувствителен к регистру, D и d - две разных переменных

если $chars_count - количество нужных символов в цифре, то проще всего сделать так:

. + ('00..0'+date.getDate()).substr(-$chars_count,$chars_count) + .

главное чтобы нулей хватало

Чем проще тема, тем больше умничают ))))

Ребят, подскажите пожалуйста как правильно составить выражение какая дата будет через определенное количество дней,

Например какая дата будет через 59 дней .

var myDate = new Date("1/1/1990"); var dayOfMonth = myDate.getDate(); myDate.setDate(dayOfMonth + 59); document.write(myDate);

Интересно так, 4 апреля - мне говорит зима.
Tue Apr 04 2017 23:20:43 GMT+1000 (RTZ 9 (зима))

function addZero(i) return ('0'+i).slice(-2)
>

как по мне удобно, быстро и просто - это:

var dNow = new Date();
var sNow = "Сегодня:" + " " + dNow.getDate() + "." + dNow.getMonth() + "." +
dNow.getFullYear();
document.write(sNow);

Источник

Javascript добавить ведущие нули на сегодняшний день

Мне нужно указать дату с начальными нулями в компоненте day и month, добавив эти правила в script. Кажется, я не могу заставить его работать.

Как хорошее соглашение, вы должны в нижнем регистре первый символ в именах переменных и резервный верблюжий корпус для объектов / прототипов.

18 ответов

var MyDate = new Date(); var MyDateString; MyDate.setDate(MyDate.getDate() + 20); MyDateString = ('0' + MyDate.getDate()).slice(-2) + '/' + ('0' + (MyDate.getMonth()+1)).slice(-2) + '/' + MyDate.getFullYear(); 

Чтобы объяснить, .slice(-2) дает нам последние два символа строки.

Итак, неважно, мы можем добавить "0" в день или месяц, и просто попросить последние два, так как они всегда те, которые мы хотим.

Читайте также:  Html terms and definitions

Итак, если MyDate.getMonth() возвращает 9 , это будет:

поэтому добавление .slice(-2) на этом дает нам два последних символа:

Но если MyDate.getMonth() возвращает 10 , это будет:

поэтому добавление .slice(-2) дает нам два последних символа или:

Может кто-нибудь объяснить, почему это лучше, чем ответ, который @Aleross дает ниже? Не сразу понятно, что он делает по сравнению с функцией pad, которая явно ясна.

Проще, просто используйте myDate.toISOString () с начальными нулями. Разобрать соответствующие части, используя подстроку.

@n00b n00b Я согласен. Это длиннее и кажется излишним. Кроме того, это выглядит хуже с точки зрения производительности (вызов slice после конкатенации выглядит дороже, чем простая конкатенация строк после сравнения), но я не выпускник информатики или что-то в этом роде. Это действительно креативное решение, но не более того, я думаю.

Путь умный. Хорошо работает для коротких, быстрых струн. Вероятно, хотите сделать что-то более производительное, если вы обрабатываете их много. В сценарии перетаскивания, перетаскивание и форматирование между несколькими метками даты / времени и отображение их на лету в движущемся окне - работает просто отлично.

@DazManCat: Это то, что он должен делать. Код начинается с добавления 20 дней к текущей дате. MyDate.setDate(MyDate.getDate() + 20);

@n00b n00b Полагаю, не обязательно лучше, просто популярнее. Я предполагаю, что если они будут расположены рядом, это будет связано с дополнительной частной функцией, необходимой для выполнения пэда.

@ n00b и @Phil Cooper, не зацикливаясь на рассуждениях о плюсах и минусах тайминга подпрограмм JavaScript, я обнаружил, что техника slice() в принятом ответе примерно на 1/10 секунды быстрее, чем @Aleross ' Техника s pad() на 1 миллион итераций. jsFiddle . "заплати свои деньги, сделай свой выбор".

Вот пример из Документов объектов даты в Mozilla Developer Network с использованием специальной функции "pad", без необходимости продления Javascript Number опытный образец. Удобной функцией, которую они дают в качестве примера, является

И ниже он используется в контексте.

/* use a function for the exact format desired. */ function ISODateString(d) < function pad(n)return d.getUTCFullYear()+'-' + pad(d.getUTCMonth()+1)+'-' + pad(d.getUTCDate())+'T' + pad(d.getUTCHours())+':' + pad(d.getUTCMinutes())+':' + pad(d.getUTCSeconds())+'Z' > var d = new Date(); console.log(ISODateString(d)); // prints something like 2009-09-28T19:03:12Z 

Очень хороший способ сделать это. Я думаю, что принятый ответ действительно хорош, но это даже чище, по моему мнению

@DavidFregoli, все эти функции даты в строку возвращают строку, поэтому, если вы вводите строку, pad выводит только строки.

Источник

Javascript getdate с нулями

Last updated: Jan 3, 2023
Reading time · 4 min

banner

# Get Month and Date in 2 Digit Format in JavaScript

To get the month and date in a 2-digit format:

  1. Use the getMonth() method to get the month of the given date.
  2. Use the getDate() method to get the day of the month of the given date.
  3. Use the padStart() method to get the values in a 2-digit format.
Copied!
const date = new Date('March 5, 2025 05:24:00'); const year = date.getFullYear(); console.log(year); // 👉️ 2025 const month = String(date.getMonth() + 1).padStart(2, '0'); console.log(month); // 👉️ 03 const day = String(date.getDate()).padStart(2, '0'); console.log(day); // 👉️ 05 const joined = [day, month, year].join('/'); console.log(joined); // 👉️ 05/03/2025

The first step is to convert the date to a string, so we can call the padStart method.

Читайте также:  Php callback function this

We used the String.padStart method to pad the month and the day of the month if necessary.

We passed the following 2 arguments to the padStart method:

  1. target length - the padStart method will return a string of this length once it has been padded.
  2. pad string - the string we want to pad our existing string with.

We know that a month and a day of the month can have up to 2 digits, so we set the target length to 2 .

Note that we have to add 1 to the return value of the getMonth method. This is because the method returns an integer between 0 (January) and 11 (December).

If the month or the day already have 2 digits, the strings get returned as is, because we've set the target length parameter to 2 .

Here's the same example where the day and the month have 2 digits, so no leading zeros are added.

Copied!
const date = new Date('October 15, 2025 05:24:00'); const year = date.getFullYear(); console.log(year); // 👉️ 2025 const month = String(date.getMonth() + 1).padStart(2, '0'); console.log(month); // 👉️ 10 const day = String(date.getDate()).padStart(2, '0'); console.log(day); // 👉️ 15 const joined = [day, month, year].join('/'); console.log(joined); // 👉️ 15/10/2025

If you have to do this often, define reusable functions.

Copied!
function getMonth2Digits(date) const month = String(date.getMonth() + 1).padStart(2, '0'); return month; > function getDay2Digits(date) const day = String(date.getDate()).padStart(2, '0'); return day; > const d = new Date('March 5, 2025 05:24:00'); const month = getMonth2Digits(d); console.log(month); // 👉️ 03 const day = getDay2Digits(d); console.log(day); // 👉️ 05

The getMonth2Digits and getDay2Digits functions take a Date object as a parameter and format the month and day to 2 digits.

As an alternative to the padStart() method, you could use a more manual approach.

# Get Month and Date in 2 Digit Format by comparing to 10

Check if the month and date are less than 10 .

If they are, add a leading zero using the addition (+) operator, otherwise, return the values directly.

Copied!
function getMonth2Digits(date) // 👇️ Add 1 because getMonth is 0-11 const month = date.getMonth() + 1; if (month 10) return '0' + month; > return month; > function getDay2Digits(date) const day = date.getDate(); if (day 10) return '0' + day; > return day; > const date = new Date('April 07, 2025 10:24:06'); console.log(getMonth2Digits(date)); // 👉️ 04 console.log(getDay2Digits(date)); // 👉️ 07

In the getMonth2Digits function, we have to add 1 to the return value of getMonth() because the method returns an integer from 0 to 11 .

Other than that, the logic is the same.

We check if the month or date is less than 10 and if they are, we prepend a leading 0 .

If they aren't, we return the values straight away.

The Date.getMonth method returns an integer between 0 (January) and 11 (December) and represents the month for a given date. Yes, unfortunately, the getMonth method is off by 1 .

Alternatively, you can use the slice() method.

# Get Month and Date in 2 Digit Format using slice()

This is a four-step process:

  1. Use the getMonth() method to get the month of the given date.
  2. Use the getDate() method to get the day of the month of the given date.
  3. Prepend a leading zero to the output of the methods.
  4. Get the last 2 characters of the result.
Copied!
function getMonth2Digits(date) const month = ('0' + (date.getMonth() + 1)).slice(-2); return month; > function getDay2Digits(date) const day = ('0' + date.getDate()).slice(-2); return day; > const d = new Date('March 5, 2025 05:24:00'); const month = getMonth2Digits(d); console.log(month); // 👉️ 03 const day = getDay2Digits(d); console.log(day); // 👉️ 05

We used the String.slice() method to format the month and date to 2 digits.

Notice that we always add a leading zero to the output of the date.getMonth() and date.getDate() methods, even if the month and day already have 2 digits.

This is why we used the String.slice() method to get the last 2 characters of the string.

The String.slice method extracts a section of a string and returns it, without modifying the original string.

The String.slice() method takes the following arguments:

Name Description
start index The index of the first character to include in the returned substring
end index The index of the first character to exclude from the returned substring

The String.slice() method can be passed negative indexes to count backward.

Copied!
const str = 'bobbyhadz.com'; console.log(str.slice(-3)); // 👉️ com console.log(str.slice(-2)); // 👉️ om

We always add a leading zero to the month or date and take the last 2 characters.

Copied!
console.log(('0' + '12').slice(-2)); // 👉️ 12 console.log(('0' + '2').slice(-2)); // 👉️ 02

The approach works regardless if the month and day consist of 1 or 2 digits.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Оцените статью