Home > Mobile >  Javascript and React Native - Date object toLocaleString doesn't output properly on Android emu
Javascript and React Native - Date object toLocaleString doesn't output properly on Android emu

Time:10-23

I'm using date_obj.toLocaleString() and it's outputting Sun Oct 17 09:57:59 2021. I'd like to have it in the format Oct 17 2021 09:57pm so that's MMM DD YYYY HH:MM AM/PM. It should also be in local time to the current device. This is running on Android emulator. How can I do this?

I tried this at it was an answer given

created.toLocaleString("en-US", {
                    year: "numeric",
                    month: "long",
                    day: "numeric",
                    hour: "numeric",
                    minute: "numeric",
                    hour12: true,
                  })

But it still hasn't changed the date. I'm also running this on React Native.

enter image description here

I also tried

options = {
  dateStyle:"medium",
  timeStyle:"short"
};

still same issue unfortunately

enter image description here

here's the current state of the code

            <Text style={{ fontSize: 13, color: "grey" }}>
              {created.toLocaleString("en-US", {
                year: "numeric",
                day: "2-digit",
                month: "short",
                hour: "2-digit",
                minute: "2-digit",
                hour12: true,
              })}
            </Text>

Still no change

CodePudding user response:

You can make use of options parameter to get the job done.

let options = {
  year:"numeric",
  day:"2-digit",
  month:"short",
  hour:"2-digit",
  minute:"2-digit",
  hour12:true,  
};
let result=(new Date('2/1/2021')).toLocaleString("en-US",options);
result=result.replaceAll(',','');
console.log(result);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Reference:

IE's toLocaleString has strange characters in results

CodePudding user response:

So I'm running this on Android apparently there's an issue with Android and Date to toLocaleString() it stops JS from doing what it wants.

  • Related