日期和时间格式取决于区域设置

发布于 2024-10-18 13:20:43 字数 495 浏览 8 评论 0原文

我对 Java 和 Android 开发都很陌生,所以这可能是一个愚蠢的问题,但我已经搜索了几天但找不到解决方案:

我尝试输出一个 java.util.Date 取决于用户的区域设置。

在 StackOverflow 上搜索,我找到了这个:

java.util.Date date = new Date();
String dateString = DateFormat.getDateFormat(getApplicationContext()).format(date);

输出:

20/02/2011

在我的法语本地化手机上。几乎没问题了。

如何使用用户的区域设置输出日期小时、分钟和秒部分?我一直在查看 android 文档,但找不到任何内容。

非常感谢。

I'm new to both Java and Android development so this might be a stupid question, but I've been searching for days now and can't find a solution:

I try to output a java.util.Date depending on the user's locale.

Searching on StackOverflow lead me to this:

java.util.Date date = new Date();
String dateString = DateFormat.getDateFormat(getApplicationContext()).format(date);

This outputs:

20/02/2011

On my french localized phone. Almost fine.

How can I also output the hours, minutes and seconds parts of the Date, using the user's locale ? I've been looking in the android documentation but couldn't find anything.

Many thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

五里雾 2024-10-25 13:20:43

使用 android.text.format.DateFormat.getTimeFormat()

参考:http://developer.android.com/reference/android/text/format/DateFormat.html

Use android.text.format.DateFormat.getTimeFormat()

ref: http://developer.android.com/reference/android/text/format/DateFormat.html

九局 2024-10-25 13:20:43

tl;dr

ZonedDateTime                                   // Represent a moment as seen in the wall-clock time used by the people of a particular region (a time zone). 
.now( ZoneId.of( "Asia/Kolkata" ) )             // Capture the current moment as seen in the specified time zone. Returns a `ZonedDateTime` object.
.format(                                        // Generate text representing the value of this `ZonedDateTime` object.
    DateTimeFormatter                           // Class controlling the generation of text representing the value of a date-time object.
    .ofLocalizedDateTime ( FormatStyle.FULL )   // Automatically localize the string representing this date-time value.
    .withLocale ( Locale.FRENCH )               // Specify the human language and cultural norms used in localizing.
)                                               // Return a `String` object.

java.time

问题中的代码使用了麻烦的旧日期时间类,这些类现在是遗留的,被 Java 8 及更高版本中内置的 java.time 类所取代。

区域设置和时区彼此无关。区域设置确定生成表示日期时间值的字符串时使用的人类语言和文化规范。时区决定了用于表示某个时刻的特定区域的挂钟时间在时间轴上。

即时 类代表 UTC 中时间轴上的时刻,分辨率为 纳秒(最多九 (9) 位小数)。

Instant instant = Instant.now();

2016-10-12T07:21:00.264Z

应用时区来获取 ZonedDateTime。我随意选择使用印度时区来显示这一时刻。同一时刻,时间轴上的同一点。

ZoneId z = ZoneId.of( "Asia/Kolkata" );
ZonedDateTime zdt = instant.atZone( z );

2016-10-12T12:51:00.264+05:30[亚洲/加尔各答]

使用加拿大魁北克省的语言环境生成字符串。让 java.time 自动本地化字符串。

Locale l = Locale.CANADA_FRENCH;
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime ( FormatStyle.FULL ).withLocale ( l );
String output = zdt.format ( f );  // Indian time zone with Québécois presentation/translation.

mercredi 2016 年 10 月 12 日 12 点 51 分(美国标准时间)


关于 java.time

java.time 框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧遗留日期时间类,例如java.util.Date, .Calendar, & java.text.SimpleDateFormat

Joda-Time 项目,现已在 维护模式,建议迁移到 java.time。

要了解更多信息,请参阅 Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规范为 JSR 310

从哪里获取 java.time 类?

ThreeTen-Extra 项目通过附加类扩展了 java.time。该项目是 java.time 未来可能添加的内容的试验场。您可能会在这里找到一些有用的类,例如 间隔YearWeek<代码>YearQuarter,以及更多

图表显示何时使用 java.time、ThreeTenABP 或 Android 脱糖 API

tl;dr

ZonedDateTime                                   // Represent a moment as seen in the wall-clock time used by the people of a particular region (a time zone). 
.now( ZoneId.of( "Asia/Kolkata" ) )             // Capture the current moment as seen in the specified time zone. Returns a `ZonedDateTime` object.
.format(                                        // Generate text representing the value of this `ZonedDateTime` object.
    DateTimeFormatter                           // Class controlling the generation of text representing the value of a date-time object.
    .ofLocalizedDateTime ( FormatStyle.FULL )   // Automatically localize the string representing this date-time value.
    .withLocale ( Locale.FRENCH )               // Specify the human language and cultural norms used in localizing.
)                                               // Return a `String` object.

java.time

The code in the Question uses troublesome old date-time classes, now legacy, supplanted by the java.time classes built into Java 8 and later.

Locale and time zone have nothing to do with each other. Locale determines the human language and cultural norms used when generating a String to represent a date-time value. The time zone determines the wall-clock time of a particular region used to represent a moment on the timeline.

The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Instant instant = Instant.now();

2016-10-12T07:21:00.264Z

Apply a time zone to get a ZonedDateTime. I arbitrarily choose to show this moment using India time zone. Same moment, same point on the timeline.

ZoneId z = ZoneId.of( "Asia/Kolkata" );
ZonedDateTime zdt = instant.atZone( z );

2016-10-12T12:51:00.264+05:30[Asia/Kolkata]

Generate a String using the locale of Québec Canada. Let java.time automatically localize the string.

Locale l = Locale.CANADA_FRENCH;
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime ( FormatStyle.FULL ).withLocale ( l );
String output = zdt.format ( f );  // Indian time zone with Québécois presentation/translation.

mercredi 12 octobre 2016 12 h 51 IST


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to java.time.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Diagram showing when to use java.time, ThreeTenABP, or Android desugaring API

樱花细雨 2024-10-25 13:20:43

java.text.DateFormat 具有您可能需要的所有功能:

DateFormat.getDateInstance()

DateFormat.getTimeInstance()

但是您需要的功能是:

DateFormat.getDateTimeInstance()
您还可以指定日期/时间部分的长度和区域设置。最终结果将是:

DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.SHORT, Locale.FRENCH).format(Date);

来源:http://docs.oracle.com/javase/7/docs/api/java/text/DateFormat.html< /a>

java.text.DateFormat has all the functions you could possibly need:

DateFormat.getDateInstance()

DateFormat.getTimeInstance()

But the one you need is:

DateFormat.getDateTimeInstance()
You can also specify the length of the date / time part and the locale. The end result would be:

DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.SHORT, Locale.FRENCH).format(Date);

Source: http://docs.oracle.com/javase/7/docs/api/java/text/DateFormat.html

夜灵血窟げ 2024-10-25 13:20:43

使用

android.text.format 包中的 getBestDateTimePattern() DateFormat.getBestDateTimePattern() 根据设置的区域设置创建最佳的日期和时间用户。

例如:骨架 EEEE, MMM d, YYYY, jj:mm 返回本地化日期和时间,如下所示。

Locale English (India):            Monday 9 Sep 2019, 9:33 PM
Locale English (United States):    Monday, Sep 9, 2019, 9:33 PM
Locale español (Estados Unidos):   lunes, 9 de sep. de 2019 9:33 PM
Locale español (México):           lunes, 9 de sep de 2019 21:33
Locale français (France):          lundi 9 sept. 2019 à 21:33
Locale português (Brasil):         segunda-feira, 9 de set de 2019 21:33

对于不同的区域设置等等。它还遵循区域设置的 12 小时或 24 小时时间格式。

要自定义您自己的骨架,请参阅 UTS #35 模式unicode.org。

示例代码

以下是 Kotlin 中经过测试的示例代码:

val skeleton = DateFormat.getBestDateTimePattern(Locale.getDefault(), "EEEE, MMM d, YYYY, jj:mm")
val formatter = SimpleDateFormat(skeleton, Locale.getDefault()).apply {
    timeZone = TimeZone.getDefault()
    applyLocalizedPattern(skeleton)
}
val dateTimeText = formatter.format(calendar.time)
Log.d("YourClass", "Locale ${Locale.getDefault().displayName}: $dateTimeText")

除了 Calendar 类,您还可以使用 ZonedDateTime 类。只需将其转换为 Date 对象并将其交给 format() 即可。例如: Date(zonedDateTime.toInstant().toEpochMilli())

希望有所帮助。

Use getBestDateTimePattern()

DateFormat.getBestDateTimePattern() from android.text.format package creates the best possible date and time according to the locale set by the user.

For example: the skeleton EEEE, MMM d, YYYY, jj:mm returns localized date and time as follows.

Locale English (India):            Monday 9 Sep 2019, 9:33 PM
Locale English (United States):    Monday, Sep 9, 2019, 9:33 PM
Locale español (Estados Unidos):   lunes, 9 de sep. de 2019 9:33 PM
Locale español (México):           lunes, 9 de sep de 2019 21:33
Locale français (France):          lundi 9 sept. 2019 à 21:33
Locale português (Brasil):         segunda-feira, 9 de set de 2019 21:33

and so on for different locales. It also respects the 12 hour or 24 hour time format of the locale.

For customizing your own skeleton refer to UTS #35 pattern on unicode.org.

Sample Code

Here's the tested sample code in Kotlin:

val skeleton = DateFormat.getBestDateTimePattern(Locale.getDefault(), "EEEE, MMM d, YYYY, jj:mm")
val formatter = SimpleDateFormat(skeleton, Locale.getDefault()).apply {
    timeZone = TimeZone.getDefault()
    applyLocalizedPattern(skeleton)
}
val dateTimeText = formatter.format(calendar.time)
Log.d("YourClass", "Locale ${Locale.getDefault().displayName}: $dateTimeText")

Instead of Calendar class, you can also use ZonedDateTime. Just convert it to Date object and give it to format(). For example: Date(zonedDateTime.toInstant().toEpochMilli())

Hope that helps.

夜夜流光相皎洁 2024-10-25 13:20:43

DateFormat.getTimeInstance() 获取具有默认区域设置的默认格式样式的时间格式化程序。您还可以传递样式和Locale

DateFormat.getTimeInstance() gets the time formatter with the default formatting style for the default locale. You can also pass a style and a Locale.

吾家有女初长成 2024-10-25 13:20:43
public static String formatDate(Date date, boolean withTime)
{
    String result = "";
    DateFormat dateFormat;

    if (date != null)
    {
        try
        {
            String format = Settings.System.getString(context.getContentResolver(), Settings.System.DATE_FORMAT);
            if (TextUtils.isEmpty(format))
            {
                dateFormat = android.text.format.DateFormat.getDateFormat(context);
            }
            else
            {
                dateFormat = new SimpleDateFormat(format);
            }
            result = dateFormat.format(date);

            if (withTime)
            {
                dateFormat = android.text.format.DateFormat.getTimeFormat(context);
                result += " " + dateFormat.format(date);
            }
        }
        catch (Exception e)
        {
        }
    }

    return result;
}
public static String formatDate(Date date, boolean withTime)
{
    String result = "";
    DateFormat dateFormat;

    if (date != null)
    {
        try
        {
            String format = Settings.System.getString(context.getContentResolver(), Settings.System.DATE_FORMAT);
            if (TextUtils.isEmpty(format))
            {
                dateFormat = android.text.format.DateFormat.getDateFormat(context);
            }
            else
            {
                dateFormat = new SimpleDateFormat(format);
            }
            result = dateFormat.format(date);

            if (withTime)
            {
                dateFormat = android.text.format.DateFormat.getTimeFormat(context);
                result += " " + dateFormat.format(date);
            }
        }
        catch (Exception e)
        {
        }
    }

    return result;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文