Android设置系统时间问题

背景及问题

  • Platform: RK3399
  • OS: Android7.1.2
  • Kernel: v4.4.103

在新的产品开发中,需要设置系统时间。发现使用老产品中的那一套报错,无法用date命令去设置,使用的代码及报错如下:

1
String.format("date -s %04d%02d%02d.%02d%02d%02d", year, month, day, hour, min, sec);

date: Unknown option s

解决及扩展

  • 后面发现在Android shell里面的date命令没有-s选项。使用help查看:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    usage: date [-u] [-r FILE] [-d DATE] [+DISPLAY_FORMAT] [-D SET_FORMAT] [SET]

    Set/get the current date/time. With no SET shows the current date.

    Default SET format is "MMDDhhmm[[CC]YY][.ss]", that's (2 digits each)
    month, day, hour (0-23), and minute. Optionally century, year, and second.
    Also accepts "@UNIXTIME[.FRACTION]" as seconds since midnight Jan 1 1970.

    -d Show DATE instead of current time (convert date format)
    -D +FORMAT for SET or -d (instead of MMDDhhmm[[CC]YY][.ss])
    -r Use modification time of FILE instead of current date
    -u Use UTC instead of current timezone

    +FORMAT specifies display format string using these escapes:

    %% literal % %n newline %t tab
    %S seconds (00-60) %M minute (00-59) %m month (01-12)
    %H hour (0-23) %I hour (01-12) %p AM/PM
    %y short year (00-99) %Y year %C century
    %a short weekday name %A weekday name %u day of week (1-7, 1=mon)
    %b short month name %B month name %Z timezone name
    %j day of year (001-366) %d day of month (01-31) %e day of month ( 1-31)
    %s seconds past the Epoch

    %U Week of year (0-53 start sunday) %W Week of year (0-53 start monday)
    %V Week of year (1-53 start monday, week < 4 days not part of this year)

    %D = "%m/%d/%y" %r = "%I : %M : %S %p" %T = "%H:%M:%S" %h = "%b"
    %x locale date %X locale time %c locale date/time
  • 在Android shell设置系统时间需使用如下命令(需要root权限):

    1
    2
    #格式为date MMddHHmmyyyy.ss set
    date 123012002018.59 set

    如需使用UTC时间,则需要加上-u选项

  • 如果需要同步更新到硬件RTC中,则还需要使用hwclock

    1
    2
    3
    4
    5
    6
    7
    8
    9
    usage: hwclock [-rswtluf]

    -f FILE Use specified device file instead of /dev/rtc (--rtc)
    -l Hardware clock uses localtime (--localtime)
    -r Show hardware clock time (--show)
    -s Set system time from hardware clock (--hctosys)
    -t Set the system time based on the current timezone (--systz)
    -u Hardware clock uses UTC (--utc)
    -w Set hardware clock from system time (--systohc)

    常用的是:

    • hwclock -w –从系统时间设置到硬件时钟
    • hwclock -s –从硬件时钟设置到系统时间
Donate comment here