程式扎記: [Linux 常見問題] HowTo Format Date For Display or Use In a Shell Script

標籤

2016年6月11日 星期六

[Linux 常見問題] HowTo Format Date For Display or Use In a Shell Script

Source From Here 
Question 
How do I format the date to display on the screen on for my shell scripts as per my requirements on Linux or Unix like operating systems? You need to use the standard date command to format date or time. You can use the same command with the shell script. The syntax reference: 
Syntax 
The syntax is as follows for the GNU/date and BSD/date command: 
date +FORMAT
OR
date +"%FORMAT"
OR
date +"%FORMAT%FORMAT"
OR
date +"%FORMAT-%FORMAT"

An operand with a leading plus (+) sign signals a user-defined format string which specifies the format in which to display the date and time. The following examples are tested on GNU/Linux, Apple OS X Unix, and FreeBSD unix operating system. 

How-To 

Task: Display date in mm-dd-yy format 
Open a terminal and type the following date command: 
# date +'%m-%d-%y'
06-12-16

To turn on 4 digit year display: 
# date +'%Y-%m-%d'
2016-06-12

Just display date as mm/dd/yy format: 
# date +'%D'
06/12/16

Task: Display time only 
Try below command: 
# date +'%T' // time; same as %H:%M:%S
13:15:04

To display locale’s 12-hour clock time, enter: 
# date +'%r' // locale’s 12-hour clock time (e.g., 11:11:04 PM)
01:16:29 PM

To display time in HH:MM format, type: 
# date +'%H-%M' // %H:hour (00..23) , %M: minute (00..59)
13-17

A sample date session 


How do I save time/date format to the shell variable? 
Simply type the following command at the shell prompt: 
# NOW=$(date +"%m-%d-%Y")
# echo $NOW
06-12-2016

Supplement 
Linux Set Date and Time From a Command Prompt

沒有留言:

張貼留言

網誌存檔

關於我自己

我的相片
Where there is a will, there is a way!