17 November 2023

Getting Date to Default to 24 Hour Format

Topics: Linux
Tags: ansible
On some of my systems the Linux _date_ command would give the time in AM/PM and on others in 24 hour notation. On my servers which are set to UTC, I strongly prefer the 24 hour time notation, it reminds me that it’s not my local time.

A previous employer of mine had started with their server clocks set to their local timezone, on which they’re continuously accumulating technical debt in their code maintaining the extra layer of timezone conversion. Learn from that mistake.

Setting the Time Zone

The easier part is setting the timezone.

# show current
timedatectl status
# see all 600 or so timezonestimedatectl
timedatectl list-timezones
# set to UTC
set-timezone UTC

Setting the Locale

The standard locale en_US.UTF-8 sets the time format to 12 hour AM/PM. It is possible to override just the time display by setting LC_TIME to a locale that defaults to 24 hour time, such as en_GB.UTF-8. The C.UTF-8 locale defaults to English with a 24 hour clock, which is what I’m currently using.

# show all known locales/languages
# If the locale you need is not present,
# on Debian family install the package: locales-alllocalectl
localectl list-locales
# override just time displaylocalectl
set-locale LC_TIME=C.UTF-8
# My preferred solution# set LC_TIME to current locale to delete LC_TIME.
set-locale C.UTF8

Setting the Time Zone With Ansible

Since this is something we want to do when setting up every server, it is just a few lines in Ansible.

roles/rolename/defaults/main.yml

...
timezone: 'UTC'
setlocale: 'C.UTF-8'

roles/rolename/tasks/settimelocale.yml

- name: Set Timeformat
  ansible.builtin.shell: "{{ item }}"
  tags:
    - timezone
  loop:
    - "localectl set-locale {{ setlocale }}"
    - "timedatectl set-timezone {{ timezone }}"