- How can I display the current time & date setting?
- How can I get the current date and time in the terminal and set a custom command in the terminal for it? [closed]
- How to write a bash script to get the time on another linux server?
- 4 Answers 4
- Related
- Hot Network Questions
- Subscribe to RSS
- How to get date and time using command line interface?
- 9 Answers 9
- Как узнать текущее время Linux
- Текущее время Linux
- С помощью date
- 2. С помощью hwclock
- 3. С помощью timedatectl
- Выводы
How can I display the current time & date setting?
I don’t know of a single file, but this may give you the info needed:
cat /etc/timezone grep UTC /etc/default/rcS date # hardware clock sudo hwclock --show
Best example (IMHO) using timedatectl (in command-line/terminal):
$ timedatectl Local time: Thu 2014-07-24 19:51:23 IST Universal time: Thu 2014-07-24 14:21:23 UTC Timezone: Asia/Kolkata (IST, +0530) NTP enabled: no NTP synchronized: no RTC in local TZ: no DST active: n/a
Visit the manpage for more settings and further information.
Additional info that may also be useful: to change time zone do «sudo timedatectl set-timezone America/Los_Angeles» (use your own time zone instead of America/Los_Angeles. Timezones can be found with timedatectl list-timezones)
Fri 22 Nov 2019 04:31:50 PM UTC
Check out info date , and for example date +’%z’
For the time zone, you can use geolocation:
$ curl https://ipapi.co/timezone America/Chicago
$ curl http://ip-api.com/line?fields=timezone America/Chicago
If you need a formatted area and time zone, you can use:
$ grep `date +%Z` /etc/timezone Etc/UTC
PS> Get-TimeZone Id : Europe/Vilnius DisplayName : (UTC+02:00) Eastern European Standard Time StandardName : Eastern European Standard Time DaylightName : Eastern European Summer Time BaseUtcOffset : 02:00:00 SupportsDaylightSavingTime : True
I suspect this won’t be popular answer in a Linux community, but I really like the verb-noun convention. It makes it easier for me to remember commands, and it will also work on all distributions with PowerShell installed 🙂
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».
How to write a bash script to get the time on another linux server?
Does anyone know how to write a bash script that will pull the time off of another server? I need a script that will poll the other server’s time and start an event at a very specific period of time based on the time on the external server.
4 Answers 4
ssh user@server.com "date +%Y%m%d%H%M%s"
This will work, assuming you have ssh access to the remote machine. Of course, ‘works’ and ‘good idea’ are not always the same thing. For instance, if anyone changes the time forward on the remote machine, you’re test will likely not fire off (assuming it should have run between the old time and the new time).
Why not just sync the time using NTP then use Cron to fire off the script at the appropriate time?
I do not have permissions to use NTP. I just need to run a few tests that fire off at a certain time on the external system.
Well this will help you if you don’t have strong time constraint.
You could write a script that will execute a script containing your command «date» In other words.
first script: remote_ssh.sh
#connect to $machine and execute the script script2execute.sh
ssh $machine bash script2execute.sh
second script:` script2execute.sh
# store your time on a file( or even a variable as you wish)
I second the use of NTP as it is the best way to get an accurate time synchronisation. You may need to install an NTP server on the external server if it doesn’t already have one.
Cron will allow you to schedule a task down to the minute level. If you need it to be scheduled to a specific second or even more accurately, then you may need to write a program to poll the time and sleep as appropriate.
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.13.43531
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
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.
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:
(The screenshot is on a virtual terminal, but it’s the same on a virtual console).
Как узнать текущее время Linux
Иногда знание текущего времени на компьютере играет большую роль, например, при отслеживании выполнения тех или иных процессов. И далеко не всегда нужную информацию можно посмотреть через системный интерфейс Linux. Поэтому существуют различные команды для терминала.
В данной статье мы расскажем про то, как узнать текущее время Linux. Заодно упомянем тему часовых поясов и синхронизацию с серверами времени.
Текущее время Linux
В системе Linux есть три удобных утилиты для определения точного времени. Наиболее продвинутой из них можно назвать date. Но и остальные имеют свои особенности.
С помощью date
Чтобы получить общую информацию, выполните команду:
Сначала выводится дата (день-число-месяц-год), время в 12-часовом формате с пометками AM (до полудня) и PM (после полудня) и часовой пояс. Информацию можно вывести в мировом UTC-формате:
Форматирование задается после знака +. Первый символ после знака % интерпретируется как один из модификаторов. А остальные символы выводятся как обычный текст. Этим можно пользоваться:
date +’Какой сегодня день? Сегодня %e число %m месяца %Y года’
Еще один пример – вывод даты в кратком виде и времени в 24-часовом формате:
Ну и не совсем стандартный вариант – вывести, какой это по счету день в году, и сам год:
date +’Сегодня %j день %Y года’
данной статьей. В ней детально описан синтаксис, опции, форматирование вывода и конкретные примеры использования. А мы переходим к следующему способу.
2. С помощью hwclock
Вообще утилита hwclock используется для настройки даты и времени в системе Linux. Но еще она подходит для простого вывода этой информации. Запускать ее следует с правами супер-пользователя:
Обратите внимание на формат вывода времени. Он включает в себя еще и миллисекунды. И через дефис указывается часовой пояс. По умолчанию это UTC. Ну а для вывода локального времени нужно добавить к команде опцию —localtime:
3. С помощью timedatectl
Еще один вариант просмотра текущего времени – использование утилиты timedatectl. Достаточно ввести команду в терминале:
Помимо даты и времени, здесь есть следующие интересующие нас поля:
- Time zone – часовой пояс.
- System clock synchronized – синхронизация часов с сервером.
- NTP service – подключение к серверу точного времени.
Выводы
Каждый из упомянутых в статье способов Как узнать текущее время Linux имеет свои особенности. Для утилиты date можно детально настроить форматирование вывода. hwclock подходит для беглого просмотра информации, ведь в основном используется для настройки. А через timedatectl получится узнать еще и статус синхронизации часов.
Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.