Linux command line 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.

Читайте также:  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 display date and time using Linux command line

To display date and time under Linux operating system using command prompt use the date command. It can also display the current time / date in the given FORMAT. We can set the system date and time as root user too.

  1. What is the command to find date and time in Linux?
  2. What is the command to show the date in Linux?
  3. Which command displays current date and time?
  4. How do I display history and time in Linux?
  5. How do I see time in terminal?
  6. How do you display date and time?
  7. How do you display the current day as full weekday?
  8. Which command displays only the current date?
  9. Who am I command in Linux?
  10. Which command displays the current date in Rdbms?
  11. How do I find my server time?
  12. How do I check my server time?

What is the command to find date and time in Linux?

date command is used to display the system date and time. date command is also used to set date and time of the system. By default the date command displays the date in the time zone on which unix/linux operating system is configured. You must be the super-user (root) to change the date and time.

What is the command to show the date in Linux?

Linux date Command Format Options

Format controls begin with the % symbol and are substituted by their current values. These are the most common formatting characters for the date command: %D – Display date as mm/dd/yy.

Which command displays current date and time?

The date command displays the current date and time. It can also be used to display or calculate a date in a format you specify.

How do I display history and time in Linux?

By default history command shows only the commands executed by users and it doesn’t print the date and time but it logs the time when you ran a command. Whenever you run history command, it looks for an environment variable called HISTTIMEFORMAT , which tells how to format date & time with history command.

How do I see time in terminal?

  1. %T: Prints the time as HH:MM:SS.
  2. %R: Prints the hour and minutes as HH:MM with no seconds, using the 24-hour clock.
  3. %r: Prints the time according to your locale, using the 12-hour clock and an am or pm indicator.
  4. %X: Prints the time according to your locale, using the 24-hour clock.
Читайте также:  Распаковать zip linux gzip

How do you display date and time?

  1. Touch and hold any empty section of a Home screen.
  2. At the bottom of the screen, tap Widgets.
  3. Touch and hold a clock widget.
  4. You’ll see images of your Home screens. Slide the clock to a Home screen.

How do you display the current day as full weekday?

  1. %a – Displays the locale’s abbreviated weekday name.
  2. %A – Displays the locale’s full weekday name.
  3. %b – Displays the locale’s abbreviated month name.
  4. %B – Displays the locale’s full month name.
  5. %c – Displays the locale’s appropriate date and time representation (default).

Which command displays only the current date?

Answer. Answer: 1: date (no option) : With no options, the date command displays the current date and time, including the abbreviated day name, abbreviated month name, day of the month, the time separated by colons, the time zone name, and the year.

Who am I command in Linux?

whoami command is used both in Unix Operating System and as well as in Windows Operating System. It is basically the concatenation of the strings “who”,”am”,”i” as whoami. It displays the username of the current user when this command is invoked. It is similar as running the id command with the options -un.

Which command displays the current date in Rdbms?

The given list is based on MySQL RDBMS.
.
SQL — Date Functions.

Sr.No. Function & Description
4 CURDATE() Returns the current date
5 CURRENT_DATE(), CURRENT_DATE Synonyms for CURDATE()

How do I find my server time?

getTime(); var currentDiff = serverTime — localTime; var currentTest = serverTime — currentDiff; var currentTime = currentTest; var eventDate = new Date(); eventDate. setDate(now. getDate() + 1); eventDate. setHours(24); eventDate.

How do I check my server time?

  1. On the server, open the webpage to show the clock.
  2. On the server, check the time and see if it matches the website.
  3. Change the time on the server, refresh the webpage. If the page changes to match the server’s new time, then you know they’re in sync.

How to Install Google Chrome on Ubuntu 18.04

Chrome

To install Google Chrome on your Ubuntu system, follow these steps:Download Google Chrome. Open your terminal either by using the Ctrl+Alt+T keyboard .

Install and Configure Monit on Ubuntu 20.04|18.04

Monit

How to Install Monit Monitoring Server on Ubuntu 20.04.Step 1 – Create an Atlantic.Net Cloud Server. First, log in to your Atlantic.Net Cloud Server. .

How to Look Up MAC Addresses

Address

Windows (two methods)Click Start and in the Search Programs and Files box type ncpa. cpl and then push Enter on your keyboard.The Network Connections .

Latest news, practical advice, detailed reviews and guides. We have everything about the Linux operating system

Источник

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

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

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

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

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

С помощью date

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

Читайте также:  Отключить поддержку шифров 3des linux

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.

Источник

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.

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

Источник

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