Вывести текущую дату linux

How to get date and time using command line interface?

How can I get current date/time in terminal. I mostly start up my system in text(console) mode and need the command to know the current date/time.

9 Answers 9

The date command will show you the date and time.

man date will show you how to control the output to whatever format you need, if you want something other than the standard output. For example:

will output the date and time in the format 14:09:22 09/06/2015

An easier to read version of the man page can be found on Ubuntu Man Pages

Time as the command line prompt:

A little fancier, enclosed in brackets:

Add the user and localhost with the time, all within brackets:

Looks like: [ DrPete on LittleSorrel 10:34 AM ~ ]

Reset prompt to default #: PS1=»# «

To make the prompt permanently available, add the prompt line of your choice, i.e.,

Can’t help it, we are rolling now. add colors, define them in .profile to make them easier to set up:

 # Install GNU coreutils bk="\[\033[0;38m\]" #means no background and white lines txtBlue="\[\033[0;34m\]" #letter color blue txtRed="\[\033[0;31m\]" #letter color red txtCyan="\[\033[1;36m\]" #letter color cyan txtWhite="\[\033[1;37m\]" #letter color white txtYellow="\[\033[1;33m\]" #letter color yellow 

Then a superfancy colored prompt would be:

PS1="[ $txtYellow\u on $txtCyan\h $txtRed\@ $txtWhite\w$bk ]" 

My first answer — so now that I am no longer a virgin — expand in what way, narrative or link to CLI prompt info?

There are a list of command used for time and date:

$ date Tue Jun 9 18:04:30 EEST 2015 
$ zdump EEST EEST Tue Jun 9 15:05:17 2015 EEST 
$ sudo hwclock Tue 09 Jun 2015 06:05:55 PM EEST -0.656710 seconds 
sudo apt-get install xview-clients 
$ ntpdate 26 Jun 10:48:34 ntpdate[4748]: no servers can be used, exiting 

With Ubuntu 15.04 (systemd) there is also timedatectl which shows you the time and allows you to change it and more in man timedatectl .

Without arguments it gives

% timedatectl Warning: Ignoring the TZ variable. Reading the system's time zone setting only. Local time: ke 2015-06-10 10:31:59 EEST Universal time: ke 2015-06-10 07:31:59 UTC RTC time: ke 2015-06-10 07:31:59 Time zone: Europe/Helsinki (EEST, +0300) NTP enabled: yes NTP synchronized: yes RTC in local TZ: no DST active: yes Last DST change: DST began at su 2015-03-29 02:59:59 EET su 2015-03-29 04:00:00 EEST Next DST change: DST ends (the clock jumps one hour backwards) at su 2015-10-25 03:59:59 EEST su 2015-10-25 03:00:00 EET

And another nice feature that I have used is timedatectl set-ntp true which activates systemd-timesyncd which is inbuild SNTP (Simple Network Time Protocol) client which syncs your clock with remote server.

Читайте также:  Картридер смарт карт linux

Although all the answers here are correct, you need to use the date command manually to see the time whenever you want, and the output will mix with normal output of your command. This is mostly ok, but sometime is not practical.

You can add the date command to your prompt which will show a (fixed) clock every time the shell is ready for the command, or you can use one of the terminal multiplexer that have a status line. My preferred one (although I admit the oldest one) is GNU screen.

In console or in a terminal, say via ssh , if you use screen, among zillions of different things you can do (I used to think about screen as unavoidable for working when I had just a text terminal) you have the option — which is normally in the default configuration — of having a clock in the status line:

Screen on a terminal

(The screenshot is on a virtual terminal, but it’s the same on a virtual console).

Источник

How to Get Current Date and Time in Bash Script

As a scripting language, Bash is widely used for system administration tasks and automation. One common task in Bash scripting is to get the current date and time. The `date` command returns the current date and time in a specific format, but you can also use a custom format string to get the date and time in any format

In this article, we will explore how to get the current date and time in a Bash script.

Getting the Current Date and Time

In Bash, you can use the date command to get the current date and time. By default, the date command will return the current date and time in the format of “Day_of_week Month Day Hour:Minute:Second Timezone Year”

date Sun Feb 28 23:26:13 UTC 2023

You can also store the output of command in a variable for further use.

Custom Format Output

There are several switches, you can use to format the output of date command.

    Get date time in “MM/DD/YY HH:MM:SS” format:

date +"%Y-%m-%d %T" 2019-03-25 14:40:32

Use Date in Shell Script:

You can simply use date command inside shell script similar to use on the command prompt. Create a bash script getDateTime.sh with the following content.

Now execute the script from command line and watch output.

./getDateTime.sh Current Date is: Mar 25, 2019 Current Date and Time is: 2019-03-25 17:18:19 Current Date and Time is: 2019-03-05 17:18:19 Current Unix epoch time is: 1488541699

Available Options with date Command:

You can find all available options of date command using –help parameter

You will find the output like below with some more options.

  • %% : a literal %
  • %a : locale’s abbreviated weekday name (e.g., Sun)
  • %A : locale’s full weekday name (e.g., Sunday)
  • %b : locale’s abbreviated month name (e.g., Jan)
  • %B : locale’s full month name (e.g., January)
  • %c : locale’s date and time (e.g., Thu Mar 3 23:05:25 2005)
  • %C : century; like %Y, except omit last two digits (e.g., 21)
  • %d : day of month (e.g, 01)
  • %D : date; same as %m/%d/%y
  • %e : day of month, space padded; same as %_d
  • %F : full date; same as %Y-%m-%d
  • %g : last two digits of year of ISO week number (see %G)
  • %G : year of ISO week number (see %V); normally useful only with %V
  • %h : same as %b
  • %H : hour (00..23)
  • %I : hour (01..12)
  • %j : day of year (001..366)
  • %k : hour ( 0..23)
  • %l : hour ( 1..12)
  • %m : month (01..12)
  • %M : minute (00..59)
  • %n : a newline
  • %N : nanoseconds (000000000..999999999)
  • %p : locale’s equivalent of either AM or PM; blank if not known
  • %P : like %p, but lower case
  • %r : locale’s 12-hour clock time (e.g., 11:11:04 PM)
  • %R : 24-hour hour and minute; same as %H:%M
  • %s : seconds since 1970-01-01 00:00:00 UTC
  • %S : second (00..60)
  • %t : a tab
  • %T : time; same as %H:%M:%S
  • %u : day of week (1..7); 1 is Monday
  • %U : week number of year, with Sunday as first day of week (00..53)
  • %V : ISO week number, with Monday as first day of week (01..53)
  • %w : day of week (0..6); 0 is Sunday
  • %W : week number of year, with Monday as first day of week (00..53)
  • %x : locale’s date representation (e.g., 12/31/99)
  • %X : locale’s time representation (e.g., 23:13:48)
  • %y : last two digits of year (00..99)
  • %Y : year
  • %z : +hhmm numeric timezone (e.g., -0400)
  • %:z : +hh:mm numeric timezone (e.g., -04:00)
  • %::z : +hh:mm:ss numeric time zone (e.g., -04:00:00)
  • %. z : numeric time zone with : to necessary precision (e.g., -04, +05:30)
  • %Z : alphabetic time zone abbreviation (e.g., EDT)
Читайте также:  Как открыть файлы на флешке в линукс

Conclusion

Getting the current date and time in a Bash script is a common task that can be accomplished using the date command. By default, the date command returns the current date and time in a specific format, but you can also use a custom format string to get the date and time in any format you like. By understanding how to use the date command in a Bash script, you can build powerful automation scripts that make use of the current date and time.

Источник

How can I get the current date and time in the terminal and set a custom command in the terminal for it? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.

This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.

I have to check the time in a Linux terminal. What is the command for getting date and time in a Linux terminal? Is there a way in which we can set a custom function?

This question seems on topic as it relates to a specific computing task on a specific operating system (which is just a software layer itself). As, @drstevens said, this is the first result in Google and it was informative for me needs. If it were off-topic, it would read something like «Do operating systems tell time?» or «What do you guys think about operating systems that tell time.» Stack Overflow is a great resource for beginners and it seems like this was closed as for being too beginner of a question. It should instead just be listed as a beginner question.

Читайте также:  Настройка сетевых папок astra linux

StackExchange is the place for answers. This is a good question. Perhaps the question should be migrated, but it should not be closed, in my opinion. This question appeared first in my Google results when I searched for «linux check time».

Источник

Как узнать текущее время Linux

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

В данной статье мы расскажем про то, как узнать текущее время Linux. Заодно упомянем тему часовых поясов и синхронизацию с серверами времени.

Текущее время Linux

В системе Linux есть три удобных утилиты для определения точного времени. Наиболее продвинутой из них можно назвать date. Но и остальные имеют свои особенности.

С помощью date

Чтобы получить общую информацию, выполните команду:

uaAAAAAASUVORK5CYII=

Сначала выводится дата (день-число-месяц-год), время в 12-часовом формате с пометками AM (до полудня) и PM (после полудня) и часовой пояс. Информацию можно вывести в мировом UTC-формате:

x8N4kMRa+TLRAAAAABJRU5ErkJggg==

Форматирование задается после знака +. Первый символ после знака % интерпретируется как один из модификаторов. А остальные символы выводятся как обычный текст. Этим можно пользоваться:

date +’Какой сегодня день? Сегодня %e число %m месяца %Y года’

nbsLHabCNnAAAAABJRU5ErkJggg==

Еще один пример – вывод даты в кратком виде и времени в 24-часовом формате:

wGHL7wpE+TiSwAAAABJRU5ErkJggg==

Ну и не совсем стандартный вариант – вывести, какой это по счету день в году, и сам год:

date +’Сегодня %j день %Y года’

B+rYAMWWlZz3AAAAABJRU5ErkJggg= https://losst.pro/komanda-date-v-linux

данной статьей. В ней детально описан синтаксис, опции, форматирование вывода и конкретные примеры использования. А мы переходим к следующему способу.

2. С помощью hwclock

Вообще утилита hwclock используется для настройки даты и времени в системе Linux. Но еще она подходит для простого вывода этой информации. Запускать ее следует с правами супер-пользователя:

h3hn3UB4SXe3PonEtcdY6y3RdZ2QxB3AVKOcMmLWCXqZ+s3OUUUfWocSLuaLnhBlnFv8YwQQtUfrD7puWY5nT09SfMAoX0eHwDNgqCVdP8tHinPWYfRedu5Irju21O9enI5G9YNLrNLTfLseeuZPP8vqJhwphxhhyYAAAAASUVORK5CYII=

Обратите внимание на формат вывода времени. Он включает в себя еще и миллисекунды. И через дефис указывается часовой пояс. По умолчанию это UTC. Ну а для вывода локального времени нужно добавить к команде опцию —localtime:

3. С помощью timedatectl

Еще один вариант просмотра текущего времени – использование утилиты timedatectl. Достаточно ввести команду в терминале:

f8PcnL6bLKipZMAAAAASUVORK5CYII=

Помимо даты и времени, здесь есть следующие интересующие нас поля:

  • Time zone – часовой пояс.
  • System clock synchronized – синхронизация часов с сервером.
  • NTP service – подключение к серверу точного времени.

Выводы

Каждый из упомянутых в статье способов Как узнать текущее время Linux имеет свои особенности. Для утилиты date можно детально настроить форматирование вывода. hwclock подходит для беглого просмотра информации, ведь в основном используется для настройки. А через timedatectl получится узнать еще и статус синхронизации часов.

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Источник

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