SNS - Web et informatique SNS - Web &
informatique
Article-javascript.webp

Display the date and time according to the language of your visitors in JS - Afficher la date et l'heure selon la langue de vos visiteurs en JavaScript

Publié le .

[EN] It may be tasteful to display the date and time based on your visitors' language on your website. Here's how to do it using JavaScript's Intl namespace object. [FR] Il peut être de bon goût d'afficher la date et l'heure en fonction de la langue de vos visiteurs sur votre site Web. Voici comment procéder à l'aide de l'objet d'espace de noms Intl de JavaScript.

// in the HTML code of your website, insert the tag which will receive the date and time
< span class="date_hour" >< /span >

// get user language
const Lang = navigator.language;

// define a time zone
const TimeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;

// interval to fire
const TimerInterval = 1000;

// create window interval
window.setInterval(

  function(){

    // new Date
    let DateNow = new Date();
    
    // define locale date
    let LocaleDateHour = new Intl.DateTimeFormat( Lang , {

      month: 'long', // values aviables: '2-digit',  'numeric',  'narrow',  'short',  'long'
      weekday: 'long', // values aviables:  'narrow',  'short',  'long'
      day: 'numeric', // values aviables: '2-digit',  'numeric'
      timeZone: TimeZone, // or 'Europe/Paris', 'America/New_York', ...
      hour: '2-digit', // values aviables: '2-digit',  'numeric'
      minute: '2-digit', // values aviables: '2-digit',  'numeric'

    }).format( DateNow );

    // append date and time to view
    document.querySelector('.date_hour').innerText = LocaleDateHour;

}, TimerInterval );

// Samples :

const Lang = 'es-ES';
const TimeZone = 'Europe/Madrid';
let DateNow = new Date();
let LocaleDateHour = new Intl.DateTimeFormat( Lang , {
      month: 'long',
      weekday: 'long',
      day: 'numeric',
      timeZone: TimeZone,
      hour: '2-digit',
      minute: '2-digit',
    }).format( DateNow );
console.log( LocaleDateHour );
// output : jueves, 14 de marzo, 15:44

const Lang = 'en-US';
const TimeZone = 'America/Los_Angeles';
let DateNow = new Date();
let LocaleDateHour = new Intl.DateTimeFormat( Lang , {
      month: 'long',
      weekday: 'long',
      day: 'numeric',
      timeZone: TimeZone,
      hour: 'numeric',
      minute: 'numeric',
    }).format( DateNow );
console.log( LocaleDateHour );
// output : Thursday, March 14 at 7:44 AM

Mots clés : Intl.DateTimeFormat JavaScript, display the date and time based on your visitors' language, internationalization constructors, Date loacale in JavaScript, afficher la date et l'heure en fonction de la langue de vos visiteurs, des constructeurs d'internationalisation et des paramètres régionaux de date en JavaScript, JavaScript tips, JS