time-utils.sh 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. #!/bin/bash
  2. # 时间工具模块
  3. # 提供网络时间获取和时间计算功能
  4. # 获取网络时间的函数
  5. get_network_time() {
  6. # 使用超时控制的curl请求
  7. local time_data
  8. local network_time
  9. # 尝试 WorldTimeAPI,超时5秒,忽略错误输出
  10. time_data=$(curl -s -m 5 "http://worldtimeapi.org/api/timezone/Asia/Tokyo" 2>/dev/null || true)
  11. if [ ! -z "$time_data" ]; then
  12. network_time=$(echo "$time_data" | grep -o '"datetime":"[^"]*"' | cut -d'"' -f4 | cut -d'.' -f1 2>/dev/null || true)
  13. if [ ! -z "$network_time" ]; then
  14. echo "$network_time"
  15. return 0
  16. fi
  17. fi
  18. # 如果第一个API失败,尝试备用API,超时5秒
  19. time_data=$(curl -s -m 5 "http://worldclockapi.com/api/json/utc/now" 2>/dev/null || true)
  20. if [ ! -z "$time_data" ]; then
  21. local utc_time=$(echo "$time_data" | grep -o '"currentDateTime":"[^"]*"' | cut -d'"' -f4 | cut -d'.' -f1 2>/dev/null || true)
  22. if [ ! -z "$utc_time" ]; then
  23. date -d "$utc_time UTC + 9 hours" "+%Y-%m-%d %H:%M:%S" 2>/dev/null || date '+%Y-%m-%d %H:%M:%S'
  24. return 0
  25. fi
  26. fi
  27. # 如果所有API都失败或超时,使用系统时间
  28. echo "[WARNING] Network time API failed, using system time" >&2
  29. date '+%Y-%m-%d %H:%M:%S'
  30. return 0
  31. }
  32. # 计算两个时间戳之间的时长(返回分钟和秒)
  33. calculate_duration() {
  34. local start_timestamp=$1
  35. local end_timestamp=$2
  36. local duration=$((end_timestamp - start_timestamp))
  37. local minutes=$((duration / 60))
  38. local seconds=$((duration % 60))
  39. echo "MINUTES=${minutes}"
  40. echo "SECONDS=${seconds}"
  41. }
  42. # 获取当前时间戳
  43. get_timestamp() {
  44. local time_str="${1:-$(date '+%Y-%m-%d %H:%M:%S')}"
  45. date -d "$time_str" +%s
  46. }