skip to Main Content
let d = new Date();    
let opts = {
  hour: '2-digit',
  minute: '2-digit',
  second: '2-digit',
  hour12: true,
};
console.log(1, Intl.DateTimeFormat('en-IN', opts).format(d));
console.log(2, Intl.DateTimeFormat('en-US', opts).format(d));

output: 1 09:15:37 am, 2 09:15:37 AM

I need to use Indian locale but am pm as capital. Is there any property to opts to set to get the desired result?

I checked that US lacale default to AM PM. Can we change to am pm?

2

Answers


  1. There is also a formatToParts() method that allows locale-aware formatting of strings produced by this Intl.DateTimeFormat object. Though I am not sure if this is what you want as you said without using string method…

    Using the formatToParts() method along with .toUpperCase() in conditional and .join()

    const d = new Date();
    
    let opts = {
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      hour12: true,
    };
    
    const meridianToUpper = (obj) => {
      // Intl.DateTimeFormat() constructor
      const dateTimeFormat = new Intl.DateTimeFormat('en-IN', opts);
      
      // get the key/value parts
      const parts = dateTimeFormat.formatToParts(obj);
      // array to store parts
      const output = [];
      // map parts and check for the meridian or "dayPeriod"
      const partValues = parts.map((p) => {
        p.type === 'dayPeriod' ? output.push(p.value.toUpperCase()) : output.push(p.value);
      });
      // return the joined array as a string
      return output.join('');
    }
    
    // pass in your date obj into the function 
    console.log(meridianToUpper(d));

    Using the formatToParts() method with .toUpperCase() as described in MDN with a switch stmt and .join()

    const formatter = new Intl.DateTimeFormat("en-IN", {
     hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      hour12: true,
    })
    
    //helper 
    const dateString = formatter
      .formatToParts(new Date())
      .map(({ type, value }) => {
        // using a switch
        switch (type) {
          case "dayPeriod":
            return value.toUpperCase();
          default:
            return value;
        }
      })
      .join("");
    
    console.log(dateString)
    Login or Signup to reply.
  2. You could check the a/p character and change to AM/PM part, this will give probably the fastest solution, which is critical with formatting many dates:

    let opts = {
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      hour12: true,
    };
    let s = Intl.DateTimeFormat('en-IN', opts).format(new Date);
    s = s.slice(0, -2) + (s[s.length - 2] === 'a' ? 'AM' : 'PM');
    
    console.log(s);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search