Location>code7788 >text

The shell script that converts UTC time and normal time

Popularity:26 ℃/2025-04-15 08:30:26

UTC time conversion shell script


Preface Feelings of fishing

Yesterday I was confused by UTC time and the system time conversion code was a little dizzy.
Finally, I won’t give up. My task that day was just to conduct an embedded test! ! ! Open the swing!
So I searched online for a long time but couldn't find the appropriate time conversion function. I &...#@##! #(#
Then, two shell scripts are born
Writing a blog at work is not called slaughtering, but technical summary! ! ! Working overtime every day, I haven't written a summary for more than a month


1. System time is converted to UTC time

#!/bin/bash

 # Get the current system time
 datetime=$(date "+%Y-%m-%d %H:%M:%S")

 # Convert to UTC timestamp (seconds) and subtract 8 hours
 timestamp=$(date -d "$datetime" +%s)
 timestamp=$((timestamp - 8 * 3600))

 # Split high and low positions
 high=$(( (timestamp >> 16) & 0xFFFF ))
 low=$(( timestamp & 0xFFFF ))

 # Print the results
 echo "System Current Time (Simulated RTC): $datetime"
 echo "UTC timestamp (seconds): $timestamp"
 printf "High: 0x%04X\n" "$high"
 printf "Low: 0x%04X\n" "$low"

 # ====================================================================
 # ====================================================================

 # Usage example:
 # 1) chmod +x ./hex_to_time.sh
 # 2)./hex_to_time.sh 0x67FF 0xD400

Time is converted into human time

I'm not a human

#!/bin/bash

 # Check the number of parameters
 if [ $# -ne 2 ]; then
   echo "Usage: $0 <high ​​16-bit hex> <low 16-bit hex>"
   echo "Example: $0 0x6800 0x3A72"
   exit 1
 fi

 # Read the input high and low bit parameters
 high_hex=$1
 low_hex=$2

 # Convert hexadecimal to decimal
 high=$((high_hex))
 low=$((low_hex))

 # Merge into 32-bit timestamp
 timestamp=$(( (high << 16) | low ))

 # Output UTC timestamp
 echo "Merge timestamp (UTC): $timestamp"

 # Local time (for RTC display)
 # If you need to add time difference, operate the timestamp here
 timestamp_local=$((timestamp))

 # Formatted as human time
 date_str=$(d "@$timestamp_local" "+%Y-%m-%d %H:%M:%S")

 echo "Local time (UTC+8): $date_str"

 # ====================================================================
 # ====================================================================

 # Usage example:
 # 1)chmod +x rtc_to_hex.sh
 # 2)./rtc_to_hex.sh