-1

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

3 Answers3

1

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);

Reference:

IE's toLocaleString has strange characters in results

The KNVB
  • 3,588
  • 3
  • 29
  • 54
1

You need to enable an International variant of JSC for Android.

After React Native 0.60, you can edit android/app/build.gradle. There is an option for changing JSC.

/**
 * The preferred build flavor of JavaScriptCore.
 *
 * For example, to use the international variant, you can use:
 * `def jscFlavor = 'org.webkit:android-jsc-intl:+'`
 *
 * The international variant includes ICU i18n library and necessary data
 * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that
 * give correct results when using with locales other than en-US.  Note that
 * this variant is about 6MiB larger per architecture than default.
 */
 - def jscFlavor = 'org.webkit:android-jsc:+'
 + def jscFlavor = 'org.webkit:android-jsc-intl:+'
0

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.