Skip to content

Instantly share code, notes, and snippets.

@cogumm
Created August 19, 2025 04:21
Show Gist options
  • Select an option

  • Save cogumm/04d00c1fb8345c376f2941106e8b320a to your computer and use it in GitHub Desktop.

Select an option

Save cogumm/04d00c1fb8345c376f2941106e8b320a to your computer and use it in GitHub Desktop.
Sincronizar data e hora do WSL2

Sincronize data e hora no WSL2 facilmente com um script simples, evitando divergências temporais e facilitando o desenvolvimento.

Se você utiliza o WSL2 (Windows Subsystem for Linux version 2) para desenvolver em JavaScript/TypeScript ou Go, pode se deparar com problemas de sincronização de data e hora entre o Linux e o Windows. Recentemente, ao depurar uma API, percebi que o comando date no WSL2 exibia uma data diferente da do Windows, o que pode causar erros sutis em testes e builds.

Embora atualizar o WSL2 resolva o problema, isso pode exigir uma reconfiguração completa do ambiente. Como alternativa, criei um script para sincronizar automaticamente a data e hora do WSL2 com o Windows, garantindo consistência sem grandes mudanças.

Como criar o script de sincronização

  1. Acesse sua pasta HOME no Ubuntu:
cd ~
  1. Crie o arquivo do script:
touch sync_time.sh
  1. Edite o arquivo com seu editor favorito (exemplo com VIM):
vim sync_time.sh
  1. Insira o seguinte código no arquivo:
#!/bin/bash
#-----------------------------------------------------------#
# Data: 19 de Agosto de 2025
# Nome: Gabriel F. Vilar (CoGUMm)
# E-mail: gabriel[at]cogumm[dot]net
# Telegram: http://t.me/CoGUMm
# Script: sync_time
# Descrição: Script de sincronização de horário.
#-----------------------------------------------------------#

YELLOW='\033[0;33m'
NC='\033[0m'
RED='\033[0;31m'

TIME_SERVER=ntp.ubuntu.com

for cmd in ntpdate; do
  if ! command -v $cmd &> /dev/null; then
      echo -e "${RED}$cmd is not installed.${NC}"
      read -p "Do you want to install $cmd? (Y/N) [Y]: " install_choice
      install_choice=${install_choice:-Y}
      if [[ "$install_choice" =~ ^[Yy]$ ]]; then
          echo -e "${YELLOW}Installing $cmd...${NC}"
          sudo apt-get update
          sudo apt-get install -y $cmd
      else
          echo -e "${RED}The script cannot continue without $cmd.${NC}"
          exit 1
      fi
  fi
done

get_offset_from_server() {
  ntpdate -q $TIME_SERVER
}

get_current_date() {
  date "+%Y-%m-%d %H:%M:%S"
}

to_epoch() {
  date -d "$1" +%s
}

sync_date() {
  echo -e "${RED}sudo ntpdate $TIME_SERVER ${NC}"
  echo
  sudo ntpdate $TIME_SERVER
  echo -e "${YELLOW}System clock synchronized.${NC}"
}

echo -e "${YELLOW}Checking system time...${NC}"

current_date=$(get_current_date)
offset=$(get_offset_from_server | head -1)

server_date=$(date -d "$current_date $offset sec" "+%Y-%m-%d %H:%M:%S")

current_epoch=$(to_epoch "$current_date")
server_epoch=$(to_epoch "$server_date")

echo -e "${YELLOW}Current system date and time: ${NC}$current_date"
echo -e "${YELLOW}Date and time from time server: ${NC}$server_date"

time_diff=$((server_epoch - current_epoch))
time_diff=${time_diff#-}

if [ "$time_diff" -gt 60 ]; then
  read -p "There is a difference of more than one minute. Do you want to synchronize? (Y/N) [Y]: " choice
  choice=${choice:-Y}
  case "$choice" in 
      Y|y ) sync_date;;
      N|n ) echo -e "${YELLOW}Synchronization skipped.${NC}";;
      * ) echo -e "${RED}Invalid option.${NC}";;
  esac
else
  echo -e "${YELLOW}The time is synchronized within one minute.${NC}"
fi
  1. Salve o arquivo e torne-o executável:
chmod +x sync_time.sh
  1. Adicione o script ao perfil do shell (exemplo com .zshrc):
vim .zshrc

No final do arquivo, adicione:

bash $HOME/sync_time.sh
  1. Salve o arquivo.

Executando o script

Com o script adicionado ao perfil do shell, ele será executado automaticamente ao abrir um novo terminal. Se houver divergência de datas, o script irá sincronizá-las. O output será semelhante a:

Checking system time...
Current system date and time: 2024-07-17 18:34:09
Date and time from Windows: 2024-07-17 18:34:09
The date and time are synchronized.

Você também pode executar o script manualmente:

cd ~
./sync_time.sh

Observação: Essa solução é um workaround temporário. Recomenda-se atualizar o WSL2 para evitar problemas futuros de sincronização de data e hora.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment