Linux terminal what time is it

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.

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.

Читайте также:  Как включить ipv6 в linux

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).

Источник

Как узнать текущее время 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 получится узнать еще и статус синхронизации часов.

Читайте также:  1c server linux debug

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

Источник

Linux Get Current Time

The time function is utilized within all operating systems like Windows, Linux, Unix, etc. You may see the current date and time at the desktop screens of your operating system within standard formats. But what about the exact current time displayed on the Linux operating system. If you are looking for a guide toward using date and time functions to display the current date and time in the Linux shell, then this article is for you. So let’s start this guide by logging in to your Ubuntu 20.04 system, as we will be performing each command on the Ubuntu 20.04 Linux shell.

After a successful login, you first need to open the Ubuntu’s terminal shell via the activity area at the desktop taskbar. Tap on it and write “terminal” in the search bar shown on your screen. The pop-up terminal screen will be shown, and you have to tap on it to open it quickly. If this process is lengthy, try using the “CTRL+Alt+T” to launch it faster. Now, your terminal will be opened within no more than 10 seconds on your screen. Let’s start with the most basic command to display the date and time of our current time zone on the shell. On executing the following command, the time has been displayed in the “hour: minute: second” format along with the time zone, i.e., PKT. It also shows the current date according to the time zone. Upon execution, you will get the output, as shown below:

If you want to only display the date on your shell with the specific format, you need to specify the format in the date command. Use the inverted commas to add the format in “%d” for day, %m for month, %y for year separated by “-” signs. This command execution shows us the date in standard “day-month-year” format. Upon execution, you will get the following output:

If you only want to display the current time on your shell using the “date” command, you must use the “+%T” character flag. On execution of this command, the current time for a specific time zone will be displayed in a standard format, i.e., “hour: minute: second”. Upon execution, you will get the output, as shown below:

If you want to display both the current and time in a single line with the time and date specification, you can also do that with the date command. So, to display the title “Date” and “Time”, we need to add “+DATE: %D” for date and “TIME: “%T” for time. The output of this instruction shows the date and time in standard format with titles of date/time on the shell. Upon execution, you will get the following output:

For example, we want to get the exact date and time of the same time zone and same time for some past year. We need to utilize the “—date” flag with the “=” sign to get the value to be searched. For example, we want to get a date and time exactly three years back for the same moment. On execution, the following instruction shows the date and time for the exact three years back, i.e., February 27, 2019:

Читайте также:  Linux mint open in terminal

Upon execution, you will get the affixed output.

If we want to take an exact date and time for the very next day on the shell, we will use the same “date” command with the “—date” flag. Use the value “tomorrow” in the inverted commas and execute the command. This will show the next exact date from the current exact date and time, i.e., February 28, 2022.

Upon execution, you will get the following output:

Upon execution, you will get the following output:

Upon execution, you will get the following output:

Upon execution, you will get the following output:

Upon execution, you will get the following output:

Another command is also known to get the current date and time for the current time zone of Linux. This command is the “timedatectl” instruction of Bash. It will not only show you the current local time but also the universal time, RTC time, your current time zone, and if the NTP services is enabled on your system. The execution of this command shows all the mentioned specifications on the shell, i.e., time and date. Upon execution, you will get the output, as shown below:

Let’s use the time zone date command to get the current time of our choice of time zone. So, we have to use the “TZ” variable with the “=” sign to get the time zone value. We want to get the current time for “Asia/Karachi” this time. The use of the “date” keyword with the “+%T” is necessary for fetching time for this time zone. We have the time displayed for the “Asia/Karachi” time zone upon execution. If you want to get the value for another time zone, use the specific time zone as a value to TZ. Let’s say we have been using the time zone “Asia/Istanbul” to get the current time for Istanbul, Turkey. The instruction shows the time for “Istanbul, Turkey” on the shell. Upon execution, you will get the following output:

$ TZ = “Asia / Karachi” date “+ % T”

$ TZ = “Asia / Istanbul” date “+ % T”

Conclusion:

In this article, we have tried to implement almost all the commands to get the current date and time for our current time zone. We have also tried to get the current time for other time zones, the past time and date, the coming date and time, and many more. You can also use %r and %R to get the current time. We hope you found this article helpful. Check the other Linux Hint articles for more tips and tutorials.

About the author

Omar Farooq

Hello Readers, I am Omar and I have been writing technical articles from last decade. You can check out my writing pieces.

Источник

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