- Timestamp To Date Converter
- Convert timestamp to date
- Convert date to timestamp
- How It Works
- Current Timestamp Examples
- Current Date and Time Examples
- Timestamp to Date Examples
- Parse Date to Timestamp Examples
- Unix Time
- Unix time конвертер (Конвертер времени Unix онлайн)
- Convert Unix timestamp to a date string
- 11 Answers 11
- convert timestamp to date in bash
- 3 Answers 3
- How to convert timestamps to dates in Bash?
- 16 Answers 16
Timestamp To Date Converter
Convert timestamp to date or date to timestamp easily
Convert timestamp to date
Convert date to timestamp
How It Works
Timestamp Online is timestamp converver between unix timestamp and human readable form date. If you want to convert timestamp, it is sufficient to either enter your timestamp into input area, or you can construct URL with your timestamp — http://timestamp.online/timestamp/
Timestamp Online also supports countdown, so you can see, how much time remains to particular timestamp. URLs for countdowns have following form — http://timestamp.online/countdown/
Current Timestamp Examples
These examples are showing how to get current unix timestamp in seconds. These examples are returning timestamp in seconds, although some of the languages are returning timestamp in milliseconds.
Current Date and Time Examples
These examples are showing how to get current date and time that could be presented to the end-user.
Timestamp to Date Examples
These examples are showing how to convert timestamp — either in milliseconds or seconds to human readable form.
Parse Date to Timestamp Examples
These examples are showing how to parse date in human readable form to unix timestamp in either milliseconds or seconds.
Unix Time
Unix time (also known as POSIX time or Epoch time) is a system for describing instants in time, defined as the number of seconds that have elapsed since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970, not counting leap seconds. It is used widely in Unix-like and many other operating systems and file formats. Because it does not handle leap seconds, it is neither a linear representation of time nor a true representation of UTC.
Источник
Unix time конвертер (Конвертер времени Unix онлайн)
Что такое Unix время или Unix эпоха (Unix epoch или Unix time или POSIX time или Unix timestamp) ?
UNIX-время или POSIX-время (англ. Unix time) — способ кодирования времени, принятый в UNIX и других POSIX-совместимых операционных системах.
Моментом начала отсчёта считается полночь (по UTC) с 31 декабря 1969 года на 1 января 1970, время с этого момента называют «эрой UNIX» (англ. Unix Epoch).
Время UNIX согласуется с UTC, в частности, при объявлении високосных секунд UTC соответствующие номера секунд повторяются.
Способ хранения времени в виде количества секунд очень удобно использовать при сравнении дат (с точностью до секунды), а также для хранения дат: при необходимости их можно преобразовать в любой удобочитаемый формат. Дата и время в этом формате также занимают очень мало места (4 или 8 байтов, в зависимости от размера машинного слова), поэтому его разумно использовать для хранения больших объёмов дат. Недостатки в производительности могут проявиться при очень частом обращении к элементам даты, вроде номера месяца и т. п. Но в большинстве случаев эффективнее хранить время в виде одной величины, а не набора полей.
Обычная дата(Human readable time) | Секунды |
1 минута | 60 секунд |
1 час | 3600 секунд |
1 день | 86400 секунд |
1 неделя | 604800 секунд |
1 месяц (30.44 дней) | 2629743 секунд |
1 год (365.24 дней) | 31556926 секунд |
Конвертивание эпохи Unix в человекопонятную дату(human readable date)
Unix дата начала и конца года, месяца или дня
Перевод секунд в дни, часы и минуты
Как получить Unix время в.
Perl | time |
PHP | time() |
Ruby | Time.now (или Time.new ). Чтобы вывести: Time.now.to_i |
Python | import time сначала, потом time.time() |
Java | long epoch = System.currentTimeMillis()/1000; |
Microsoft .NET C# | epoch = (DateTime.Now.ToUniversalTime().Ticks — 621355968000000000) / 10000000; |
VBScript/ASP | DateDiff(«s», «01/01/1970 00:00:00», Now()) |
Erlang | calendar:datetime_to_gregorian_seconds(calendar:now_to_universal_time( now()))-719528*24*3600. |
MySQL | SELECT unix_timestamp(now()) |
PostgreSQL | SELECT extract(epoch FROM now()); |
SQL Server | SELECT DATEDIFF(s, ‘1970-01-01 00:00:00’, GETUTCDATE()) |
JavaScript | Math.round(new Date().getTime()/1000.0) getTime() возвращает время в миллисекундах. |
Unix/Linux | date +%s |
Другие OS | Командная строка: perl -e «print time» (Если Perl установлен на вашей системе) |
Конвертирование даты в Unix время в.
PHP | mktime(часы, минуты, секунды, месяц, день, год) |
Ruby | Time.local(год, месяц, день, часы, минуты, секунды, usec ) (или Time.gm для GMT/UTC вывода). Чтобы вывести добавьте .to_i |
Python | import time сначала, потом int(time.mktime(time.strptime(‘2000-01-01 12:34:00’, ‘%Y-%m-%d %H:%M:%S’))) |
Java | long epoch = new java.text.SimpleDateFormat («dd/MM/yyyy HH:mm:ss»).parse(«01/01/1970 01:00:00»); |
VBScript/ASP | DateDiff(«s», «01/01/1970 00:00:00», поле даты) |
MySQL | SELECT unix_timestamp(время) Формат времени: YYYY-MM-DD HH:MM:SS или YYMMDD или YYYYMMDD |
PostgreSQL | SELECT extract(epoch FROM date(‘2000-01-01 12:34’)); С timestamp: SELECT EXTRACT(EPOCH FROM TIMESTAMP WITH TIME ZONE ‘2001-02-16 20:38:40-08’); C интервалом: SELECT EXTRACT(EPOCH FROM INTERVAL ‘5 days 3 hours’); |
SQL Server | SELECT DATEDIFF(s, ‘1970-01-01 00:00:00’, поле с датой) |
Unix/Linux | date +%s -d»Jan 1, 1980 00:00:01″ |
Конвертирование Unix времеми в понятную дату(human readable date).
PHP | date(Формат, unix время); |
Ruby | Time.at(unix время) |
Python | import time сначала, потом time.strftime(«%a, %d %b %Y %H:%M:%S +0000», time.localtime(unix время)) Замените time.localtime на time.gmtime для GMT даты. |
Java | String date = new java.text.SimpleDateFormat(«dd/MM/yyyy HH:mm:ss»).format(new java.util.Date (unix время*1000)); |
VBScript/ASP | DateAdd(«s», unix время, «01/01/1970 00:00:00») |
PostgreSQL | SELECT TIMESTAMP WITH TIME ZONE ‘epoch’ + unix время * INTERVAL ‘1 second’; |
MySQL | from_unixtime(unix время, не обязательно, выходной формат) Стандартный формат выхода YYY-MM-DD HH:MM:SS |
SQL Server | DATEADD(s, unix время, ‘1970-01-01 00:00:00’) |
Microsoft Excel | =(A1 / 86400) + 25569 Результат будет в GMT зоне времени. Для других временных зон: =((A1 +/- разница аремени для зоны) / 86400) + 25569. |
Linux | date -d @1190000000 |
Другие OS | Командная строка: perl -e «print scalar(localtime(unix время))» (Если установлен Perl) Замените ‘localtime’ на ‘gmtime’ для GMT/UTC зоны времени. |
Для чего нужен инструмент «Unixtime конвертер»?
Данный инструмент, в первую очередь, будет полезен веб-мастерам, которые постоянно имеют дело с большими объемами дат или часто в своей работе обращаются к их элементам. С помощью инструмента «Unixtime конвертер» можно легко конвертировать Unix время в понятную для пользователя дату (и наоборот), узнать текущее Unix epoch время, а также получить Unix время в различных языках программирования, СУБД и операционных системах.
Что такое Unix время?
Эра Unix (Unix epoch) началась в ночь с 31 декабря 1969 года на 1 января 1970 года. Именно эту дату взяли за точку отсчета «компьютерного» времени, которое исчисляется в секундах и занимает очень мало места на диске – всего 4 или 8 байт. С помощью такого способа кодирования программисты могут «спрятать» любую дату в одно число, и легко конвертировать его обратно в понятный пользователям формат.
Unix время (еще его называют Unix time или POSIX time) удобно использовать в различных операционных системах и языках программирования, так как оно отображается в виде одной величины, а не определенного количества полей, занимающих место. К тому же, UNIX time полностью соответствует стандарту UTC (в том числе и в високосных годах) – в таком случае соответствующие значения секунд просто повторяются.
Пару слов о терминах.
Итак, Unix-временем (или POSIX-временем) считается количество секунд, которые прошли с полуночи 1 января 1970 года до настоящего времени.
Unix Timestamp (временная метка) – это «зафиксированное» время, иными словами – конкретная дата, запечатленная в числе.
UTC (Universal Coordinated Time) – это Всемирное координированное время, которое «фиксируется» на нулевом меридиане, и от которого ведется отсчет географических часовых поясов.
Насколько «долговечна» данная система?
Всего лишь через пару десятков лет, а именно 19 января 2038 года в 03:14:08 по UTC Unix time достигнет значения 2147483648, и компьютерные системы могут интерпретировать это число как отрицательное. Ключ к решению данной проблемы лежит в использовании 64-битной (вместо 32-битной) переменной для хранения времени. В таком случае, запаса числовых значений Unix time хватит человечеству еще на 292 миллиарда лет. Неплохо, правда?
Unix время – одно для всех
Если вы живете в Лондоне или Сан-Франциско, а ваши друзья – в Москве, то «сверить часы» можно по Unix time: эта система в данный момент времени едина для всего мира. Естественно, если время на серверах выставлено правильно. А с помощью инструмента «Unixtime конвертер» такая конвертация займет у вас доли секунды.
Источник
Convert Unix timestamp to a date string
Is there a quick, one-liner way to convert a Unix timestamp to a date from the Unix command line?
date might work, except it’s rather awkward to specify each element (month, day, year, hour, etc.), and I can’t figure out how to get it to work properly. It seems like there might be an easier way — am I missing something?
11 Answers 11
With GNU’s date you can do:
On OS X, use date -r .
Alternatively, use strftime() . It’s not available directly from the shell, but you can access it via gawk. The %c specifier displays the timestamp in a locale-dependent manner.
date -d @1278999698 +’%Y-%m-%d %H:%M:%S’ Where the number behind @ is the number in seconds
This solution works with versions of date which do not support date -d @ . It does not require AWK or other commands. A Unix timestamp is the number of seconds since Jan 1, 1970, UTC so it is important to specify UTC.
If you are on a Mac, then use:
Command for getting epoch:
As @TomMcKenzie says in a comment to another answer, date -r 123456789 is arguably a more common (i.e. more widely implemented) simple solution for times given as seconds since the Unix Epoch, but unfortunately there’s no universal guaranteed portable solution.
The -d option on many types of systems means something entirely different than GNU Date’s —date extension. Sadly GNU Date doesn’t interpret -r the same as these other implementations. So unfortunately you have to know which version of date you’re using, and many older Unix date commands don’t support either option.
Even worse, POSIX date recognizes neither -d nor -r and provides no standard way in any command at all (that I know of) to format a Unix time from the command line (since POSIX Awk also lacks strftime() ). (You can’t use touch -t and ls because the former does not accept a time given as seconds since the Unix Epoch.)
Note though The One True Awk available direct from Brian Kernighan does now have the strftime() function built-in as well as a systime() function to return the current time in seconds since the Unix Epoch), so perhaps the Awk solution is the most portable.
Источник
convert timestamp to date in bash
i have time logs in timestamp (epoch unix time) format :
i would like to convert it to a regular date like
any ideas what approach would be the fastest?
this takes awful lot of time and just appends the current time
3 Answers 3
Another approach that must be much faster , using printf of bash version >4.2 :
For datefmt you need a string accepted by strftime(3) — see man 3 strftime
In this case , printf format string is:
%F Equivalent to %Y-%m-%d (the ISO 8601 date format). (C99)
%H The hour as a decimal number using a 24-hour clock (range 00 to 23).(Calculated from tm_hour.)
%M The minute as a decimal number (range 00 to 59). (Calculated from tm_min.)
%S The second as a decimal number (range 00 to 60). (The range is up to 60 to allow for occasional leap seconds.- Calculated from tm_sec.)
Update to remove milliseconds:
The way to transform epoch to date is date -d @epochtime +format
An alternative way is to use date —file switch to read dates from a file directly.
In order date to understand that these lines are epoch time you need to add @ in the beginning of each line.
This can be done like bellow:
Alternativelly, you can do it on the fly without affecting the original file:
PS: in this case —file reads from — == stdin == pipe
In both cases, the result is
PS: by the way, the timestamps you provide seems invalid, since it seems to refer at year 49990
Источник
How to convert timestamps to dates in Bash?
I need a shell command or script that converts a Unix timestamp to a date. The input can come either from the first parameter or from stdin, allowing for the following usage patterns:
Both commands should output «Wed Mar 3 13:38:49 2010».
16 Answers 16
On later versions of common Linux distributions you can use:
works for me on Mac OS X.
% date —help | grep — -r -r, —reference=FILE display the last modification time of FILE
This version is similar to chiborg’s answer, but it eliminates the need for the external tty and cat . It uses date , but could just as easily use gawk . You can change the shebang and replace the double square brackets with single ones and this will also run in sh .
You can use GNU date, for example,
You can use this simple awk script:
Since Bash 4.2 you can use printf ‘s %(datefmt)T format:
That’s nice, because it’s a shell builtin. The format for datefmt is a string accepted by strftime(3) (see man 3 strftime ). Here %c is:
%c The preferred date and time representation for the current locale.
Now if you want a script that accepts an argument and, if none is provided, reads stdin, you can proceed as:
You can get formatted date from timestamp like this
I use this when converting log files or monitoring them:
In OSX, or BSD, there’s an equivalent -r flag which apparently takes a unix timestamp. Here’s an example that runs date four times: once for the first date, to show what it is; one for the conversion to unix timestamp with %s , and finally, one which, with -r , converts what %s provides back to a string.
Источник