📅  最后修改于: 2023-12-03 14:43:55.023000             🧑  作者: Mango
As a programmer, you may often come across situations where you need to convert dates between various formats. This can be especially challenging when dealing with different platforms and tools such as Linux, Epoch, and Excel. However, with Shell or Bash scripting, you can easily automate the date conversion process.
Linux Epoch time is a widely used timestamp format that represents the number of seconds that have elapsed since January 1, 1970 (00:00:00 UTC). In Bash, you can use the date
command to convert the Epoch time to human-readable format, and vice versa.
To convert a Unix timestamp to a human-readable date string, use the following syntax:
date -d @<timestamp>
For example, to convert the timestamp 1589894400
(which represents May 19, 2020), run:
$ date -d @1589894400
This will output:
Tue May 19 00:00:00 UTC 2020
To convert a human-readable date string to Epoch time, use the following syntax:
date -d "<date>" +%s
For example, to convert the date "May 19, 2020" to Epoch time, run:
$ date -d "May 19, 2020" +%s
This will output:
1589827200
Excel uses a different method to represent dates, known as the Excel Serial Date Number. This is a decimal value that represents the number of days that have elapsed since January 1, 1900. To convert dates between Excel and Unix Timestamp formats, you can use a simple Bash script along with some basic math.
#!/bin/bash
# Excel Serial Date Number to Unix Timestamp
function excel_to_unix() {
# Days between 1900-01-01 and 1970-01-01
EPOCH_OFFSET=$((25569))
# Seconds per day
DAY_IN_SECONDS=$((24*3600))
echo $((( $1 - $EPOCH_OFFSET ) * $DAY_IN_SECONDS ))
}
# Unix Timestamp to Excel Serial Date Number
function unix_to_excel() {
# Days between 1900-01-01 and 1970-01-01
EPOCH_OFFSET=$((25569))
# Seconds per day
DAY_IN_SECONDS=$((24*3600))
echo $(( $1/$DAY_IN_SECONDS + $EPOCH_OFFSET ))
}
# Convert Excel Serial Date Number to Unix Timestamp
excel_to_unix 43934.0
# Convert Unix Timestamp to Excel Serial Date Number
unix_to_excel 1616513404
This script defines two functions, excel_to_unix
and unix_to_excel
, which can be used to convert dates between Excel and Unix Timestamp formats. To use this script, simply copy the code into a file, and run it using Bash.
For example, to convert the Excel date 43934.0
(which represents May 19, 2020) to Unix Timestamp, run:
$ bash excel_unix_date_converter.sh
This will output:
1589827200
To convert the Unix Timestamp 1616513404
to Excel date format, run:
$ bash excel_unix_date_converter.sh
This will output:
44401
In this tutorial, we have shown how to convert dates between various formats using Shell or Bash scripting. With these techniques, you can easily automate the date conversion process and streamline your workflow.