Функции для работы с датой и временем в VBA Excel. Синтаксис, параметры, спецсимволы, примеры. Функции, возвращающие текущие дату и время по системному таймеру.
Функция Date
Date – это функция, которая возвращает значение текущей системной даты. Тип возвращаемого значения – Variant/Date.
Синтаксис
Пример
Sub PrimerDate() MsgBox «Сегодня: « & Date End Sub |
Функция DateAdd
DateAdd – это функция, которая возвращает результат прибавления к дате указанного интервала времени. Тип возвращаемого значения – Variant/Date.
Синтаксис
DateAdd(interval, number, date) |
Параметры
Параметр | Описание |
---|---|
interval | Обязательный параметр. Строковое выражение из спецсимволов, представляющее интервал времени, который требуется добавить. |
number | Обязательный параметр. Числовое выражение, задающее количество интервалов, которые необходимо добавить. Может быть как положительным (возвращается будущая дата), так и отрицательным (возвращается предыдущая дата). |
date | Обязательный параметр. Значение типа Variant/Date или литерал, представляющий дату, к которой должен быть добавлен интервал. |
Таблицу аргументов (значений) параметра interval
смотрите в параграфе «Приложение 1».
Примечание к таблице аргументов: три символа – y, d, w – указывают функции DateAdd
на один день, который необходимо прибавить к исходной дате number
раз.
Пример
Sub PrimerDateAdd() MsgBox «31.01.2021 + 1 месяц = « & DateAdd(«m», 1, «31.01.2021») ‘Результат: 28.02.2021 MsgBox «Сегодня + 3 года = « & DateAdd(«yyyy», 3, Date) MsgBox «Сегодня — 2 недели = « & DateAdd(«ww», —2, Date) MsgBox «10:22:14 + 10 минут = « & DateAdd(«n», 10, «10:22:14») ‘Результат: 10:32:14 End Sub |
Функция DateDiff
DateDiff – это функция, которая возвращает количество указанных интервалов времени между двумя датами. Тип возвращаемого значения – Variant/Long.
Синтаксис
DateDiff(interval, date1, date2, [firstdayofweek], [firstweekofyear]) |
Параметры
Параметр | Описание |
---|---|
interval | Обязательный параметр. Строковое выражение из спецсимволов, представляющее интервал времени, количество которых (интервалов) требуется вычислить между двумя датами. |
date1, date2 | Обязательные параметры. Значения типа Variant/Date , представляющие две даты, между которыми вычисляется количество указанных интервалов. |
firstdayofweek | Необязательный параметр. Константа, задающая первый день недели. По умолчанию – воскресенье. |
firstweekofyear | Необязательный параметр. Константа, задающая первую неделю года. По умолчанию – неделя, в которую входит 1 января. |
Таблицу аргументов (значений) параметра interval
смотрите в параграфе «Приложение 1».
Примечание к таблице аргументов: в отличие от функции DateAdd
, в функции DateDiff
спецсимвол "w"
, как и "ww"
, обозначает неделю. Но расчет осуществляется по разному. Подробнее об этом на сайте разработчиков.
Параметры firstdayofweek
и firstweekofyear
определяют правила расчета количества недель между датами.
Таблицы констант из коллекций firstdayofweek
и firstweekofyear
смотрите в параграфах «Приложение 2» и «Приложение 3».
Пример
Sub PrimerDateDiff() ‘Даже если между датами соседних лет разница 1 день, ‘DateDiff с интервалом «y» покажет разницу — 1 год MsgBox DateDiff(«y», «31.12.2020», «01.01.2021») ‘Результат: 1 год MsgBox DateDiff(«d», «31.12.2020», «01.01.2021») ‘Результат: 1 день MsgBox DateDiff(«n», «31.12.2020», «01.01.2021») ‘Результат: 1440 минут MsgBox «Полных лет с начала века = « & DateDiff(«y», «2000», Year(Now) — 1) End Sub |
Функция DatePart
DatePart – это функция, которая возвращает указанную часть заданной даты. Тип возвращаемого значения – Variant/Integer.
Есть предупреждение по использованию этой функции.
Синтаксис
DatePart(interval, date, [firstdayofweek], [firstweekofyear]) |
Параметры
Параметр | Описание |
---|---|
interval | Обязательный параметр. Строковое выражение из спецсимволов, представляющее часть даты, которую требуется извлечь. |
date | Обязательные параметры. Значение типа Variant/Date , представляющее дату, часть которой следует извлечь. |
firstdayofweek | Необязательный параметр. Константа, задающая первый день недели. По умолчанию – воскресенье. |
firstweekofyear | Необязательный параметр. Константа, задающая первую неделю года. По умолчанию – неделя, в которую входит 1 января. |
Таблицу аргументов (значений) параметра interval
смотрите в параграфе «Приложение 1». В третьей графе этой таблицы указаны интервалы значений, возвращаемых функцией DatePart
.
Таблицы констант из коллекций firstdayofweek
и firstweekofyear
смотрите в параграфах «Приложение 2» и «Приложение 3».
Пример
Sub PrimerDatePart() MsgBox DatePart(«y», «31.12.2020») ‘Результат: 366 MsgBox DatePart(«yyyy», CDate(43685)) ‘Результат: 2019 MsgBox DatePart(«n», CDate(43685.45345)) ‘Результат: 52 MsgBox «День недели по счету сегодня = « & DatePart(«w», Now, vbMonday) End Sub |
Функция DateSerial
DateSerial – это функция, которая возвращает значение даты для указанного года, месяца и дня. Тип возвращаемого значения – Variant/Date.
Синтаксис
DateSerial(year, month, day) |
Параметры
Параметр | Описание |
---|---|
year | Обязательный параметр типа Integer. Числовое выражение, возвращающее значение от 100 до 9999 включительно. |
month | Обязательный параметр типа Integer. Числовое выражение, возвращающее любое значение (в пределах Integer), а не только от 1 до 12.* |
day | Обязательный параметр типа Integer. Числовое выражение, возвращающее любое значение (в пределах Integer), а не только от 1 до 31.* |
* Функция DateSerial автоматически пересчитывает общее количество дней в полные месяцы и остаток, общее количество месяцев в полные годы и остаток (подробнее в примере).
Пример
Sub PrimerDateSerial() MsgBox DateSerial(2021, 2, 10) ‘Результат: 10.02.2020 MsgBox DateSerial(2020, 1, 400) ‘Результат: 03.02.2021 End Sub |
Разберем подробнее строку DateSerial(2020, 1, 400)
:
- 400 дней = 366 дней + 31 день + 3 дня;
- 366 дней = 1 год, так как по условию month:=1, значит февраль 2020 входит в расчет, а в нем – 29 дней;
- 31 день = 1 месяц, так как сначала заполняется январь (по условию month:=1);
- 3 дня – остаток.
В итоге получается:
DateSerial(2020+1, 1+1, 3) = DateSerial(2021, 2, 3)
Функция DateValue
DateValue – это функция, которая преобразует дату, указанную в виде строки, в значение типа Variant/Date (время игнорируется).
Синтаксис
Параметр date
– строковое выражение, представляющее дату с 1 января 100 года по 31 декабря 9999 года.
Пример
Sub PrimerDateValue() MsgBox DateValue(«8 марта 2021») ‘Результат: 08.03.2021 MsgBox DateValue(«17 мая 2021 0:59:15») ‘Результат: 17.05.2021 End Sub |
Функция DateValue игнорирует время, указанное в преобразуемой строке, но если время указано в некорректном виде (например, «10:60:60»), будет сгенерирована ошибка.
Функция Day
Day – это функция, которая возвращает день месяца в виде числа от 1 до 31 включительно. Тип возвращаемого значения – Variant/Integer.
Синтаксис
Параметр date
– любое числовое или строковое выражение, представляющее дату.
Пример
Sub PrimerDay() MsgBox Day(Now) End Sub |
Функция IsDate
IsDate – это функция, которая возвращает True, если выражение является датой или распознается как допустимое значение даты или времени. В остальных случаях возвращается значение False.
Синтаксис
Параметр expression
– это переменная, возвращающая дату или строковое выражение, распознаваемое как дата или время.
Значение, возвращаемое переменной expression, не должно выходить из диапазона допустимых дат: от 1 января 100 года до 31 декабря 9999 года (для Windows).
Пример
Sub PrimerIsDate() MsgBox IsDate(«18 апреля 2021») ‘Результат: True MsgBox IsDate(«31 февраля 2021») ‘Результат: False MsgBox IsDate(«4.10.20 11:12:54») ‘Результат: True End Sub |
Функция Hour
Hour – это функция, которая возвращает количество часов в виде числа от 0 до 23 включительно. Тип возвращаемого значения – Variant/Integer.
Синтаксис
Параметр time
– любое числовое или строковое выражение, представляющее время.
Пример
Sub PrimerHour() MsgBox Hour(Now) MsgBox Hour(«22:36:54») End Sub |
Функция Minute
Minute – это функция, которая возвращает количество минут в виде числа от 0 до 59 включительно. Тип возвращаемого значения – Variant/Integer.
Синтаксис
Параметр time
– любое числовое или строковое выражение, представляющее время.
Пример
Sub PrimerMinute() MsgBox Minute(Now) MsgBox Minute(«22:36:54») End Sub |
Функция Month
Month – это функция, которая возвращает день месяца в виде числа от 1 до 12 включительно. Тип возвращаемого значения – Variant/Integer.
Синтаксис
Параметр date
– любое числовое или строковое выражение, представляющее дату.
Пример
Sub PrimerMonth() MsgBox Month(Now) End Sub |
Функция MonthName
MonthName – это функция, которая возвращает название месяца в виде строки.
Синтаксис
MonthName(month, [abbreviate]) |
Параметры
Параметр | Описание |
---|---|
month | Обязательный параметр. Числовое обозначение месяца от 1 до 12 включительно. |
abbreviate | Необязательный параметр. Логическое значение: True – возвращается сокращенное название месяца, False (по умолчанию) – название месяца не сокращается. |
Пример
Sub PrimerMonthName() MsgBox MonthName(10) ‘Результат: Октябрь MsgBox MonthName(10, True) ‘Результат: окт End Sub |
Функция Now
Now – это функция, которая возвращает текущую системную дату и время. Тип возвращаемого значения – Variant/Date.
Синтаксис
Пример
Sub PrimerNow() MsgBox Now MsgBox Day(Now) MsgBox Hour(Now) End Sub |
Функция Second
Second – это функция, которая возвращает количество секунд в виде числа от 0 до 59 включительно. Тип возвращаемого значения – Variant/Integer.
Синтаксис
Параметр time
– любое числовое или строковое выражение, представляющее время.
Пример
Sub PrimerSecond() MsgBox Second(Now) MsgBox Second(«22:30:14») End Sub |
Функция Time
Time – это функция, которая возвращает значение текущего системного времени. Тип возвращаемого значения – Variant/Date.
Синтаксис
Пример
Sub PrimerTime() MsgBox «Текущее время: « & Time End Sub |
Функция TimeSerial
TimeSerial – это функция, которая возвращает значение времени для указанного часа, минуты и секунды. Тип возвращаемого значения – Variant/Date.
Синтаксис
TimeSerial(hour, minute, second) |
Параметры
Параметр | Описание |
---|---|
hour | Обязательный параметр типа Integer. Числовое выражение, возвращающее значение от 0 до 23 включительно. |
minute | Обязательный параметр типа Integer. Числовое выражение, возвращающее любое значение (в пределах Integer), а не только от 0 до 59.* |
second | Обязательный параметр типа Integer. Числовое выражение, возвращающее любое значение (в пределах Integer), а не только от 0 до 59.* |
* Функция TimeSerial автоматически пересчитывает общее количество секунд в полные минуты и остаток, общее количество минут в полные часы и остаток (подробнее в примере).
Пример
Sub PrimerTime() MsgBox TimeSerial(5, 16, 4) ‘Результат: 5:16:04 MsgBox TimeSerial(5, 75, 158) ‘Результат: 6:17:38 End Sub |
Разберем подробнее строку TimeSerial(5, 75, 158)
:
- 158 секунд = 120 секунд (2 минуты) + 38 секунд;
- 75 минут = 60 минут (1 час) + 15 минут.
В итоге получается:
TimeSerial(5+1, 15+2, 38) = TimeSerial(6, 17, 38)
Функция TimeValue
TimeValue – это функция, которая преобразует время, указанное в виде строки, в значение типа Variant/Date (дата игнорируется).
Синтаксис
Параметр time
– строковое выражение, представляющее время с 0:00:00 по 23:59:59 включительно.
Пример
Sub PrimerTimeValue() MsgBox TimeValue(«6:45:37 PM») ‘Результат: 18:45:37 MsgBox TimeValue(«17 мая 2021 3:59:15 AM») ‘Результат: 3:59:15 End Sub |
Функция TimeValue игнорирует дату, указанную в преобразуемой строке, но если дата указана в некорректном виде (например, «30.02.2021»), будет сгенерирована ошибка.
Функция Weekday
Weekday – это функция, которая возвращает день недели в виде числа от 1 до 7 включительно. Тип возвращаемого значения – Variant/Integer.
Синтаксис
Weekday(date, [firstdayofweek]) |
Параметры
Параметр | Описание |
---|---|
date | Обязательный параметр. Любое выражение (числовое, строковое), отображающее дату. |
firstdayofweek | Константа, задающая первый день недели. По умолчанию – воскресенье. |
Таблицу констант из коллекции firstdayofweek
смотрите в параграфе «Приложение 2».
Пример
Sub PrimerWeekday() MsgBox Weekday(«23 апреля 2021», vbMonday) ‘Результат: 5 MsgBox Weekday(202125, vbMonday) ‘Результат: 6 End Sub |
Функция WeekdayName
WeekdayName – это функция, которая возвращает название дня недели в виде строки.
Синтаксис
WeekdayName(weekday, [abbreviate], [firstdayofweek]) |
Параметры
Параметр | Описание |
---|---|
weekday | Обязательный параметр. Числовое обозначение дня недели от 1 до 7 включительно. |
abbreviate | Необязательный параметр. Логическое значение: True – возвращается сокращенное название дня недели, False (по умолчанию) – название дня недели не сокращается. |
firstdayofweek | Константа, задающая первый день недели. По умолчанию – воскресенье. |
Таблицу констант из коллекции firstdayofweek
смотрите в параграфе «Приложение 2».
Пример
Sub PrimerWeekdayName() MsgBox WeekdayName(3, True, vbMonday) ‘Результат: Ср MsgBox WeekdayName(3, , vbMonday) ‘Результат: среда MsgBox WeekdayName(Weekday(Now, vbMonday), , vbMonday) End Sub |
Функция Year
Year – это функция, которая возвращает номер года в виде числа. Тип возвращаемого значения – Variant/Integer.
Синтаксис
Параметр date
– любое числовое или строковое выражение, представляющее дату.
Пример
Sub PrimerYear() MsgBox Year(Now) End Sub |
Приложение 1
Таблица аргументов (значений) параметраinterval
для функций DateAdd
, DateDiff
и DatePart
:
Аргумент | Описание | Интервал значений |
---|---|---|
yyyy | Год | 100 – 9999 |
q | Квартал | 1 – 4 |
m | Месяц | 1 – 12 |
y | День года | 1 – 366 |
d | День месяца | 1 – 31 |
w | День недели | 1 – 7 |
ww | Неделя | 1 – 53 |
h | Часы | 0 – 23 |
n | Минуты | 0 – 59 |
s | Секунды | 0 – 59 |
В третьей графе этой таблицы указаны интервалы значений, возвращаемых функцией DatePart
.
Приложение 2
Константы из коллекции firstdayofweek
:
Константа | Значение | Описание |
---|---|---|
vbUseSystem | 0 | Используются системные настройки |
vbSunday | 1 | Воскресенье (по умолчанию) |
vbMonday | 2 | Понедельник |
vbTuesday | 3 | Вторник |
vbWednesday | 4 | Среда |
vbThursday | 5 | Четверг |
vbFriday | 6 | Пятница |
vbSaturday | 7 | Суббота |
Приложение 3
Константы из коллекции firstweekofyear
:
Константа | Значение | Описание |
---|---|---|
vbUseSystem | 0 | Используются системные настройки. |
vbFirstJan1 | 1 | Неделя, в которую входит 1 января (по умолчанию). |
vbFirstFourDays | 2 | Неделя, в которую входит не менее четырех дней нового года. |
vbFirstFullWeek | 3 | Первая полная неделя года. |
Format numbers as dates or times
Excel for Microsoft 365 Excel for Microsoft 365 for Mac Excel for the web Excel 2021 Excel 2021 for Mac Excel 2019 Excel 2019 for Mac Excel 2016 Excel 2016 for Mac Excel 2013 Excel 2010 Excel 2007 Excel for Mac 2011 More…Less
When you type a date or time in a cell, it appears in a default date and time format. This default format is based on the regional date and time settings that are specified in Control Panel, and changes when you adjust those settings in Control Panel. You can display numbers in several other date and time formats, most of which are not affected by Control Panel settings.
In this article
-
Display numbers as dates or times
-
Create a custom date or time format
-
Tips for displaying dates or times
Display numbers as dates or times
You can format dates and times as you type. For example, if you type 2/2 in a cell, Excel automatically interprets this as a date and displays 2-Feb in the cell. If this isn’t what you want—for example, if you would rather show February 2, 2009 or 2/2/09 in the cell—you can choose a different date format in the Format Cells dialog box, as explained in the following procedure. Similarly, if you type 9:30 a or 9:30 p in a cell, Excel will interpret this as a time and display 9:30 AM or 9:30 PM. Again, you can customize the way the time appears in the Format Cells dialog box.
-
On the Home tab, in the Number group, click the Dialog Box Launcher next to Number.
You can also press CTRL+1 to open the Format Cells dialog box.
-
In the Category list, click Date or Time.
-
In the Type list, click the date or time format that you want to use.
Note: Date and time formats that begin with an asterisk (*) respond to changes in regional date and time settings that are specified in Control Panel. Formats without an asterisk are not affected by Control Panel settings.
-
To display dates and times in the format of other languages, click the language setting that you want in the Locale (location) box.
The number in the active cell of the selection on the worksheet appears in the Sample box so that you can preview the number formatting options that you selected.
Top of Page
Create a custom date or time format
-
On the Home tab, click the Dialog Box Launcher next to Number.
You can also press CTRL+1 to open the Format Cells dialog box.
-
In the Category box, click Date or Time, and then choose the number format that is closest in style to the one you want to create. (When creating custom number formats, it’s easier to start from an existing format than it is to start from scratch.)
-
In the Category box, click Custom. In the Type box, you should see the format code matching the date or time format you selected in the step 3. The built-in date or time format can’t be changed or deleted, so don’t worry about overwriting it.
-
In the Type box, make the necessary changes to the format. You can use any of the codes in the following tables:
Days, months, and years
To display |
Use this code |
---|---|
Months as 1–12 |
m |
Months as 01–12 |
mm |
Months as Jan–Dec |
mmm |
Months as January–December |
mmmm |
Months as the first letter of the month |
mmmmm |
Days as 1–31 |
d |
Days as 01–31 |
dd |
Days as Sun–Sat |
ddd |
Days as Sunday–Saturday |
dddd |
Years as 00–99 |
yy |
Years as 1900–9999 |
yyyy |
If you use «m» immediately after the «h» or «hh» code or immediately before the «ss» code, Excel displays minutes instead of the month.
Hours, minutes, and seconds
To display |
Use this code |
---|---|
Hours as 0–23 |
h |
Hours as 00–23 |
hh |
Minutes as 0–59 |
m |
Minutes as 00–59 |
mm |
Seconds as 0–59 |
s |
Seconds as 00–59 |
ss |
Hours as 4 AM |
h AM/PM |
Time as 4:36 PM |
h:mm AM/PM |
Time as 4:36:03 P |
h:mm:ss A/P |
Elapsed time in hours; for example, 25.02 |
[h]:mm |
Elapsed time in minutes; for example, 63:46 |
[mm]:ss |
Elapsed time in seconds |
[ss] |
Fractions of a second |
h:mm:ss.00 |
AM and PM If the format contains an AM or PM, the hour is based on the 12-hour clock, where «AM» or «A» indicates times from midnight until noon and «PM» or «P» indicates times from noon until midnight. Otherwise, the hour is based on the 24-hour clock. The «m» or «mm» code must appear immediately after the «h» or «hh» code or immediately before the «ss» code; otherwise, Excel displays the month instead of minutes.
Creating custom number formats can be tricky if you haven’t done it before. For more information about how to create custom number formats, see Create or delete a custom number format.
Top of Page
Tips for displaying dates or times
-
To quickly use the default date or time format, click the cell that contains the date or time, and then press CTRL+SHIFT+# or CTRL+SHIFT+@.
-
If a cell displays ##### after you apply date or time formatting to it, the cell probably isn’t wide enough to display the data. To expand the column width, double-click the right boundary of the column containing the cells. This automatically resizes the column to fit the number. You can also drag the right boundary until the columns are the size you want.
-
When you try to undo a date or time format by selecting General in the Category list, Excel displays a number code. When you enter a date or time again, Excel displays the default date or time format. To enter a specific date or time format, such as January 2010, you can format it as text by selecting Text in the Category list.
-
To quickly enter the current date in your worksheet, select any empty cell, and then press CTRL+; (semicolon), and then press ENTER, if necessary. To insert a date that will update to the current date each time you reopen a worksheet or recalculate a formula, type =TODAY() in an empty cell, and then press ENTER.
Need more help?
You can always ask an expert in the Excel Tech Community or get support in the Answers community.
Need more help?
I have a very large excel spread sheet that has a column of time stamps. Does anyone know convert that over to a date? Is there a function I can use? I tried format cell date but that doesn’t work. My file is 91,568 KB. If there is a simpler way to this that would be great. I’m open to ideas.
Thank you in advance
P.S.
I don’t know any programming languages
asked Apr 17, 2013 at 21:50
3
A timestamp is the elapsed time since Epoch time (01/01/1970), so basically we have to convert this time in days, and add the epoch time, to get a valid format for any Excel like spreadsheet software.
-
From a timestamp in milliseconds (ex: 1488380243994)
use this formula:
=A1/1000/86400+25569
with this formater:
yyyy-mm-dd hh:mm:ss.000
-
From a timestamp in seconds (ex: 1488380243)
use this formula:
=A1/86400+25569
with this formater:
yyyy-mm-dd hh:mm:ss
Where A1
is your column identifier.
Given custom formaters allow to not loose precision in displayed data, but you can of course use any other date/time one that corresponds to your needs.
answered Oct 18, 2018 at 14:21
DonatelloDonatello
3,4153 gold badges31 silver badges38 bronze badges
1
below formula worked form me in MS EXEL
=TEXT(CELL_VALUE/24/60/60/1000 + 25569,"YYYY-MM-DD HH:MM")
CELL_VALUE is timestamp in milliseconds
here is explanation for text function.
answered Nov 22, 2018 at 10:31
ranjeetcaoranjeetcao
1,7232 gold badges20 silver badges28 bronze badges
1
If you get a Error 509 in Libre office you may replace ,
by ;
in the DATE() function
=(((COLUMN_ID_HERE/60)/60)/24)+DATE(1970;1;1)
answered Apr 24, 2014 at 20:36
Karl AdlerKarl Adler
15.3k10 gold badges69 silver badges86 bronze badges
1
If your file is really big try to use following formula:
=A1 / 86400 + 25569
A1 should be replaced to what your need.
Should work faster than =(((COLUMN_ID_HERE/60)/60)/24)+DATE(1970,1,1) cause of less number of calculations needed.
answered Feb 22, 2014 at 17:29
1
=(((A1/60)/60)/24)+DATE(1970,1,1)+(-5/24)
assuming A1
is the cell where your time stamp is located and dont forget to adjust to account for the time zone you are in (5 assuming you are on EST)
answered Apr 15, 2014 at 19:51
LanaLana
711 silver badge1 bronze badge
This DATE
-thing won’t work in all Excel-versions.
=CELL_ID/(60 * 60 * 24) + "1/1/1970"
is a save bet instead.
The quotes are necessary to prevent Excel from calculating the term.
answered Sep 19, 2016 at 6:21
Stephan WeinholdStephan Weinhold
1,6151 gold badge28 silver badges37 bronze badges
Be aware of number of digits in epoch time. Usually they are ten (1534936923) ,then use:
=(A1 / 86400) + 25569
For thirteen digits (1534936923000) of epoch time adjust the formula:
=(LEFT(A1,LEN(A1)-3) / 86400) + 25569
to avoid
###################################
Dates or times that are negative or too large display as ######
See more on https://www.epochconverter.com/
answered Jul 23, 2019 at 7:15
Daniel HorvathDaniel Horvath
3411 gold badge3 silver badges13 bronze badges
The answer of @NeplatnyUdaj is right but consider that Excel want the function name in the set language, in my case German. Then you need to use «DATUM» instead of «DATE»:
=(((COLUMN_ID_HERE/60)/60)/24)+DATUM(1970,1,1)
answered Oct 18, 2018 at 14:44
ownkingownking
1,9461 gold badge23 silver badges34 bronze badges
AD ticks to datetime format: =A1/864000000000 — 109205
answered Dec 15, 2015 at 13:20
i got result from this in LibreOffice Calc :
=DATE(1970,1,1)+Column_id_here/60/60/24
answered Jan 31, 2016 at 7:30
This worked for me:
=(col_name]/60/60/24)+(col_name-1)
deblocker
7,6092 gold badges23 silver badges57 bronze badges
answered Mar 3, 2017 at 8:28
Use this simple formula. It works.
Suppose time stamp in A2
:
=DATE(YEAR(A2),MONTH(A2),DAY(A2))
4b0
21.7k30 gold badges95 silver badges140 bronze badges
answered Dec 23, 2019 at 8:12
1
Excel stores date and time values as serial numbers in the back end.
This means that while you may see a date such as “10 January 2020” or “01/10/2020” in a cell, in the back-end, Excel is storing that as a number. This is useful as it also allows users to easily add/subtract date and time in Excel.
In Microsoft Excel for Windows, “01 Jan 1900” is stored as 1, “02 Jan 1900” is stored as 2, and so on.
Below, both columns have the same numbers, but Column A shows numbers and Column B shows the date that’s represented by that number.
This is also the reason that sometimes you may expect a date in a cell but end up seeing a number. I see this happening all the time when I download data from databases or web-based tools.
It happens when the cell format is set to show a number as a number instead of a date.
So how can we convert these serial numbers into dates?
That’s what this tutorial is all about.
In this tutorial, I would show you two really easy ways to convert serial numbers into dates in Excel
Note: Excel for Windows uses the 1900 date system (which means that 1 would represent 01 Jan 1900, while Excel for Mac uses the 1904 date system (which men’s that 1 would represent 01 Jan 1904 in Excel in Mac)
So let’s get started!
Convert Serial Numbers to Dates Using Number Formatting
The easiest way to convert a date serial number into a date is by changing the formatting of the cells that have these numbers.
You can find some of the commonly used date formats in the Home tab in the ribbon
Let me show you how to do this.
Using the In-Built Date Format Options in the Ribbon
Suppose you have a data set as shown below, and you want to convert all these numbers in column A into the corresponding date that it represents.
Below are the steps to do this:
- Select the cells that have the number that you want to convert into a date
- Click the ‘Home’ tab
- In the ‘Number’ group, click on the Number Formatting drop-down
- In the drop-down, select ‘Long Date’ or Short Date’ option (based on what format would you want these numbers to be in)
That’s it!
The above steps would convert the numbers into the selected date format.
The above steps have not changed the value in the cell, only the way it’s being displayed.
Note that Excel picks up the short date formatting based on your system’s regional setting. For example, if you’re in the US, then the date format would be MM/DD/YYYY, and if you are in the UK, then the date format would be DD/MM/YYYY.
While this is a quick method to convert serial numbers into dates, it has a couple of limitations:
- There are only two date formats – short date and long date (and that too in a specific format). So, if you want to only get the month and the year and not the day, you won’t be able to do that using these options.
- You cannot show date as well as time using the formatting options in the drop-down. You can either choose to display the date or the time but not both.
So, if you need more flexibility in the way you want to show dates in Excel, you need to use the Custom Number Formatting option (covered next in this tutorial).
Sometimes when you convert a number into a date in Excel, instead of the date you may see some hash signs (something like #####). this happens when the column width is not enough to accommodate the entire date. In such a case, just increase the width of the column.
Creating a Custom Date Format Using Number Formatting Dialog Box
Suppose you have a data set as shown below and you want to convert the serial numbers in column A into dates in the following format – 01.01.2020
Note that this option is not available by default in the ribbon method that we covered earlier.
Below are the steps to do this:
- Select the cells that have the number that you want to convert into a date
- Click the ‘Home’ tab
- In the Numbers group, click on the dialog box launcher icon (it’s a small tilted arrow at the bottom right of the group)
- In the ‘Format Cells’ dialog box that opens up, make sure the ‘Number’ tab selected
- In the ‘Category’ options on the left, select ‘Date’
- Select the desired formatting from the ‘Type’ box.
- Click OK
The above steps would convert the numbers into the selected date format.
As you can see, there are more date formatting options in this case (as compared with the short and long date we got with the ribbon).
And in case you do not find the format you are looking for, you can also create your own date format.
For example, let’s say that I want to show the date in the following format – 01/01/2020 (which is not already an option in the format cells dialog box).
Here is how I can do this:
- Select the cells that have the numbers that you want to convert into a date
- Click the Home tab
- In the Numbers group, click on the dialog box launcher icon (it’s a small tilt arrow at the bottom right of the group)
- In the ‘Format Cells’ dialog box that opens up, make sure the ‘Number’ tab selected
- In the ‘Category’ options on the left, select ‘Custom’
- In the field on the right, enter
mm/dd/yyyy
- Click OK
The above steps would change all the numbers into the specified number format.
With custom format, you get full control and it allows you to show the date in whatever format you want. You can also create a format where it shows the date as well time in the same cell.
For example, in the same example, if you want to show date as well as time, you can use the below format:
mm/dd/yyyy hh:mm AM/PM
Below is the table that shows the date format codes you can use:
Date Formatting Code | How it Formats the Date |
m | Shows the Month as a number from 1–12 |
mm | Show the months as two-digit numbers from 01–12 |
mmm | Shows the Month as three-letter as in Jan–Dec |
mmmm | Shows the Months full name as in January–December |
mmmmm | Shows the Month name first alphabet as in J-D |
d | Shows Days as 1–31 |
dd | Shows Days as 01–31 |
ddd | Shows Days as Sun–Sat |
dddd | Shows Days as Sunday–Saturday |
yy | Shows Years as 00–99 |
yyyy | Shows Years as 1900–9999 |
Also read: How to Convert Text to Date in Excel (Easy Formulas)
Convert Serial Numbers to Dates Using TEXT Formula
The methods covered above work by changing the formatting of the cells that have the numbers.
But in some cases, you may not be able to use these methods.
For example, below I have a data set where the numbers have a leading apostrophe – which converts these numbers into text.
If you try and using the inbuilt options to change the formatting of the cells with this data set, it would not do anything. This is because Excel does not consider these as numbers, and since dates for numbers, Excel refuses your wish to format these.
In such a case, you can either convert these text to numbers and then use the above-covered formatting methods, or use another technique to convert serial numbers into dates – using the TEXT function.
The TEXT function takes two arguments – the number that needs to be formatted, and the format code.
Suppose you have a data set as shown below, and you want to convert all the numbers and column A into dates.
Below the formula that could do that:
=TEXT(A2,"MM/DD/YYYY")
Note that in the formula I have specified the date formatting to be in the MM/DD/YYYY format. If you need to use any other formatting, you can specify the code for it as the second argument of the TEXT formula.
You can also use this formula to show the date as well as the time.
For example, if you want the final result to be in the format – 01/01/2020 12:00 AM, use the below formula:
=TEXT(A2,"mm/dd/yyyy hh:mm AM/PM")
In the above formula, I have added the time format as well so if there are decimal parts in the numbers, it would be shown as the time in hours and minutes.
If you only want the date (and not the underlying formula), convert the formulas into static values by using paste special.
One big advantage of using the TEXT function to convert serial numbers into dates is that you can combine the TEXT formula result with other formulas. For example, you can combine the resulting date with the text and show something such as – The Due Date is 01-Jan-2020 or The Deadline is 01-Jan-2020
Note: Remember dates and time are stored as numbers, where every integer number would represent one full day and the decimal part would represent that much part of the day. So 1 would mean 1 full day and 0.5 would mean half-a-day or 12 hours.
So these are two simple ways you can use to convert serial numbers to dates in Microsoft Excel.
I hope you found this tutorial useful!
Other Excel tutorials you may like:
- How to SUM values between two dates (using SUMIFS formula)
- How to Stop Excel from Changing Numbers to Dates Automatically
- How to Remove Time from Date/Timestamp in Excel
- Calculate the Number of Months Between Two Dates in Excel
- Excel DATEVALUE Function – Convert Date in Text into Serial Date Formats
- How to Convert Numbers to Text in Excel
- How to Compare Dates in Excel (Greater/Less Than, Mismatches)
- Convert Scientific Notation to Number or Text in Excel
- How To Convert Date To Serial Number In Excel?
Как преобразовать ячейку формата даты / времени в дату только в Excel?
Если вы хотите преобразовать ячейку формата даты и времени только в значение даты, такое как 2016/4/7 1:01 AM до 2016/4/7, эта статья может вам помочь.
Преобразование ячейки формата даты / времени в дату только с помощью формулы
Легко удаляйте все времена из дат всего несколькими щелчками мыши
Преобразование ячейки формата даты/времени в дату только с помощью Kutools for Excel
Преобразование ячейки формата даты / времени в дату только с помощью формулы
Следующая формула поможет вам преобразовать ячейку формата даты / времени в дату только в Excel.
1. Выберите пустую ячейку, в которую вы поместите значение даты, затем введите формулу. = МЕСЯЦ (A2) & «/» & ДЕНЬ (A2) & «/» & ГОД (A2) в строку формул и нажмите Enter .
2. Вы можете видеть, что только значение даты заполняется в выбранной ячейке на основе ячейки даты / времени. Продолжайте выбирать ячейку даты, затем перетащите маркер заполнения вниз, чтобы отобразить все даты, основанные на других ячейках даты / времени. Смотрите скриншот:
Легко удаляйте все времена из дат всего несколькими щелчками мыши
В этом разделе показано, как легко удалить все время из выбранных ячеек даты с помощью утилиты «Удалить время из даты» Kutools for Excel. Пожалуйста, сделайте следующее.
1. Выберите пустую ячейку для определения даты после удаления времени из (говорит C2). Нажмите Кутулс > Формула Помощник > Формула Помощник. Смотрите скриншот:
2. в Помощник по формулам диалоговое окно, настройте следующим образом.
- В разделе Выберите формулу коробка, найдите и выберите Удалить время из даты;
Tips: Вы можете проверить Фильтр введите определенное слово в текстовое поле, чтобы быстро отфильтровать формулу. - Выберите ячейку с датой и временем, вам нужно сохранить только дату в DateTime коробка;
- Нажмите OK кнопку.
3. Продолжайте выбирать первую ячейку результата, затем перетащите маркер заполнения вниз, чтобы получить все результаты, как вам нужно, как показано ниже:
Теперь все времена удалены из указанных дат.
Если вы хотите получить бесплатную пробную версию (30-день) этой утилиты, пожалуйста, нажмите, чтобы загрузить это, а затем перейдите к применению операции в соответствии с указанными выше шагами.
Преобразование ячейки формата даты/времени в дату только с помощью Kutools for Excel
Вот рекомендую удобный инструмент — Kutools for Excel, С этими Применить форматирование даты Утилита, вы можете легко преобразовать ячейку формата даты / времени в любой формат даты, который вам нужен.
1. Выберите ячейку формата даты / времени, в которой будет отображаться только значение даты, затем щелкните Кутулс > Формат > Применить форматирование даты. Смотрите скриншот:
2. в Применить форматирование даты диалоговом окне выберите формат даты в Форматирование даты поле, а затем щелкните OK кнопку.
Теперь ячейки формата даты / времени отображаются только как значение даты. Смотрите скриншот:
Внимание: Хотя ячейки формата даты / времени отображаются только как дата, отображаемые значения в строке формул по-прежнему имеют формат даты / времени. Если вы хотите преобразовать значения, отображаемые в строке формул, в их фактические значения, выберите их и щелкните Кутулс > К фактическому. Смотрите скриншот:
Если вы хотите получить бесплатную пробную версию (30-день) этой утилиты, пожалуйста, нажмите, чтобы загрузить это, а затем перейдите к применению операции в соответствии с указанными выше шагами.
Преобразование ячейки формата даты / времени только в дату
Статьи по теме:
- Как изменить американский формат даты в Excel?
Лучшие инструменты для работы в офисе
Kutools for Excel Решит большинство ваших проблем и повысит вашу производительность на 80%
- Снова использовать: Быстро вставить сложные формулы, диаграммы и все, что вы использовали раньше; Зашифровать ячейки с паролем; Создать список рассылки и отправлять электронные письма …
- Бар Супер Формулы (легко редактировать несколько строк текста и формул); Макет для чтения (легко читать и редактировать большое количество ячеек); Вставить в отфильтрованный диапазон…
- Объединить ячейки / строки / столбцы без потери данных; Разделить содержимое ячеек; Объединить повторяющиеся строки / столбцы… Предотвращение дублирования ячеек; Сравнить диапазоны…
- Выберите Дубликат или Уникальный Ряды; Выбрать пустые строки (все ячейки пустые); Супер находка и нечеткая находка во многих рабочих тетрадях; Случайный выбор …
- Точная копия Несколько ячеек без изменения ссылки на формулу; Автоматическое создание ссылок на несколько листов; Вставить пули, Флажки и многое другое …
- Извлечь текст, Добавить текст, Удалить по позиции, Удалить пробел; Создание и печать промежуточных итогов по страницам; Преобразование содержимого ячеек в комментарии…
- Суперфильтр (сохранять и применять схемы фильтров к другим листам); Расширенная сортировка по месяцам / неделям / дням, периодичности и др .; Специальный фильтр жирным, курсивом …
- Комбинируйте книги и рабочие листы; Объединить таблицы на основе ключевых столбцов; Разделить данные на несколько листов; Пакетное преобразование xls, xlsx и PDF…
- Более 300 мощных функций. Поддерживает Office/Excel 2007-2021 и 365. Поддерживает все языки. Простое развертывание на вашем предприятии или в организации. Полнофункциональная 30-дневная бесплатная пробная версия. 60-дневная гарантия возврата денег.
Вкладка Office: интерфейс с вкладками в Office и упрощение работы
- Включение редактирования и чтения с вкладками в Word, Excel, PowerPoint, Издатель, доступ, Visio и проект.
- Открывайте и создавайте несколько документов на новых вкладках одного окна, а не в новых окнах.
- Повышает вашу продуктивность на 50% и сокращает количество щелчков мышью на сотни каждый день!