Automatically set timezone and time via location?

Hey guys so iam working on a software project with a friend and to prevent unneeded user input for the time zone data i was wondering what is the most effective way to automatically set the date and time zone data via the command line interface.

Here is the code from a project I am working on that uses bash to do this. I guess bonus that it does locale for you too. (this is for Arch but you can modify for your distro):

# this uses the API to pull timezone - should be okay
#
hrdclck () {
  clear
  timedatectl set-ntp true
  MYTMZ="$(curl -s https://ipapi.co/timezone)"
}
# this uses API to pull language /  country
localestg () {
  clear
  LCLGET1=$(curl -s https://ipapi.co/languages | head -c 2)
  LCLGET2=$(curl -s https://ipapi.co/country | head -c 2)
  LCLST="${LCLGET1}"_"${LCLGET2}"
}


systmzone () {
  clear
  arch-chroot /mnt hwclock --systohc --utc
  arch-chroot /mnt timedatectl set-ntp true
  arch-chroot /mnt rm -rf /etc/localtime
  arch-chroot /mnt ln -sf /usr/share/zoneinfo/"${MYTMZ}" /etc/localtime
  clear
}
#
syslocale () {
  clear
  echo ""${LCLST}".UTF-8 UTF-8" >> /mnt/etc/locale.gen
  echo "LANG="${LCLST}".UTF-8" > /mnt/etc/locale.conf
  arch-chroot /mnt locale-gen
  arch-chroot /mnt localectl set-locale LANG="${LCLST}".UTF-8
  clear
}

Thanks! but whats up with the chroot commands? “arch-chroot”

arch-chroot is for when you are doing an automated install specifically for arch, (same with the use of /mnt) you can cut these parts out depending on your use case. It was just easier for me to cut out the sections and post em.

aahhhh ok, i am a Gentoo user here. Have experience with most of the common based distro commands but Arch. Thanks for the script, will do a btrfs snapshot and will try to reconstruct something a bit more stream line for a quick timezone / time update. If anyone else has any other recommended scripts that they have on hand just post them here.

BTW thanks for the quick reply.

1 Like