skip to Main Content

How can I get the string dd.mm.yyyy in JavaScript and convert it depending on the user’s locale (for example, дд.мм.гггг)? Is it possible with the help of internal functions, or will you have to write your own converter?

I tried to find a solution in Datе and Intl.DateTimeFormat, but I didn’t find it there.

3

Answers


  1. I don’t think you will be able to do this without a hard coded function. But maybe something like that can fit your needs:

    const date = new Date();
    const options = { day: '2-digit', month: '2-digit', year: 'numeric' };
    const formattedDate = date.toLocaleDateString(undefined, options);
    

    Here the documentation for more options.

    If you need to get the format from a string, you’ll need to use a library like moment:

    moment('2016-01-01 00:00:00').creationData().format
    

    https://momentjs.com/docs/#/parsing/creation-data/

    Login or Signup to reply.
  2. The answer is no. There is no way you can get дд.мм.гггг from _RU or dd/mm/åååå for Norway/Denmark using plain JS/INTL

    Here is the closest you can get using a lookup table with a locale as input

    const localizedPlaceholders = {
        'ru-RU': 'дд.мм.гггг',  // Russian
        'no-NO': 'dd/mm/åååå',  // Norwegian
        'da-DK': 'dd/mm/åååå',  // Danish
        'en-US': 'MM/dd/yyyy',  // US English
        'en-GB': 'dd/MM/yyyy',  // British English
        // Add other locales as needed
    };
    const deflt = 'en-GB'
    const getDatePlaceholder = (locale) => localizedPlaceholders[locale] || localizedPlaceholders[deflt]
    
    
    console.log(getDatePlaceholder('ru-RU')); // Output: "дд.мм.гггг"
    console.log(getDatePlaceholder('no-NO')); // Output: "dd/mm/åååå"
    console.log(getDatePlaceholder('da-DK')); // Output: "dd/mm/åååå"
    console.log(getDatePlaceholder('en-US')); // Output: "MM/dd/yyyy"
    console.log(getDatePlaceholder('xx-YY')); // Output: "dd/MM/yyyy"

    Here is IMNHO OK hack for moment

    const getDDMMYYY = locale => {
      const m = moment('2016-01-01 00:00:00').locale(locale);
      let { d: day, M: month, y: year } = m.creationData().locale._relativeTime;
    
      // If we get a function instead of a string, call it
      if (typeof day === 'function') {
        day = day(1, false, 'd', false); // Call with parameters to get the singular form
        month = month(1, false, 'M', false); // Call with parameters to get the singular form
        year = year(1, false, 'y', false); // Call with parameters to get the singular form
      }
    
      // "a day" "en dag" etc
      if (day.split(' ').length > 1) day = day.split(' ')[1];
      if (month.split(' ').length > 1) month = month.split(' ')[1];
      if (year.split(' ').length > 1) year = year.split(' ')[1];
    
      // Extract and double the first letter
      const dd = day.slice(0, 1).repeat(2);       // дд or tt
      const mm = month.slice(0, 1).repeat(2);     // мм
      const yyyy = year.slice(0, 1).repeat(4);    // гггг or jjjj
    
      return `${dd}.${mm}.${yyyy}`;
    };
    
    console.log(getDDMMYYY('ru')); // Output: "дд.мм.гггг"
    console.log(getDDMMYYY('da')); // Output: "dd.mm.åååå"
    console.log(getDDMMYYY('no')); // Output: "dd.mm.åååå"
    console.log(getDDMMYYY('nl')); // Output: "dd.mm.jjjj"
    console.log(getDDMMYYY('fr')); // Output: "dd.mm.aaaa"
    console.log(getDDMMYYY('de')); // Output: "TT.MM.JJJJ"
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.30.1/moment-with-locales.min.js" integrity="sha512-4F1cxYdMiAW98oomSLaygEwmCnIP38pb4Kx70yQYqRwLVCs3DbRumfBq82T08g/4LJ/smbFGFpmeFlQgoDccgg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    Login or Signup to reply.
  3. You can try using the lang attribute, but browsers are unlikely to implement it. Second-best is to have a placeholder being changed based on the chosen language:

    function getLocale(that) {
        switch (that.value) {
            case 'hu': return 'yyyy/mm/dd';
            case 'en': return 'mm/dd/yyyy';
            default: return 'mm/dd/yyyy'
        }
    }
    
    function changelang(that) {
        document.getElementById("datepicker").placeholder = getLocale(that);
    }
    <label for="datepicker">Select Date:</label>
    <select onchange="changelang(this)">
        <option value="hu">HU</option>
        <option value="en">EN</option>
    </select>
    <input type="text" id="datepicker" lang="hu" onfocus="(this.type='date')" onblur="(this.type='text')" placeholder="yyyy/mm/dd">
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search