将 Java SQL 日期从 yyyy-MM-dd 转换为 dd MMMM yyyy 格式的最佳方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3178690/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 17:07:34  来源:igfitidea点击:

Best way to convert Java SQL Date from yyyy-MM-dd to dd MMMM yyyy format

javadateformat

提问by Mr Morgan

Is there a straightforward way of converting a Java SQL Date from format yyyy-MM-dd to dd MMMM yyyy format?

是否有一种直接的方法可以将 Java SQL 日期从格式 yyyy-MM-dd 转换为 dd MMMM yyyy 格式?

I could convert the date to a string and then manipulate it but I'd rather leave it as a Java SQL Date. at the time I need to do this, the data has already been read from the MySQL database so I cant do the change there.

我可以将日期转换为字符串,然后对其进行操作,但我宁愿将其保留为 Java SQL 日期。当我需要这样做时,数据已经从 MySQL 数据库中读取,所以我无法在那里进行更改。

采纳答案by Jesper

Object such as java.sql.Dateand java.util.Date(of which java.sql.Dateis a subclass) don't have a format of themselves. You use a java.text.DateFormatobject to display these objects in a specific format, and it's the DateFormat(not the Dateitself) that determines the format.

诸如java.sql.Dateandjava.util.Datejava.sql.Date类的对象(其是子类)没有自己的格式。您可以使用java.text.DateFormat对象以特定格式显示这些对象,而决定格式的是DateFormat(而不是其Date本身)。

For example:

例如:

Date date = ...;  // wherever you get this
DateFormat df = new SimpleDateFormat("dd MMMM yyyy");
String text = df.format(date);
System.out.println(text);

Note: When you print a Dateobject without using a DateFormatobject, like this:

注意:当您在Date不使用对象的情况下打印DateFormat对象时,如下所示:

Date date = ...;
System.out.println(date);

then it will be formatted using some default format. That default format is however not a property of the Dateobject that you can change.

然后它将使用一些默认格式进行格式化。但是,该默认格式不是Date您可以更改的对象的属性。

回答by Jon Skeet

It's not clear what you mean by a "Java SQL Date". If you mean as in java.sql.Date, then it doesn't really havea string format... it's just a number. To format it ina particular way, use something like java.text.SimpleDateFormat.

不清楚“Java SQL 日期”是什么意思。如果你的意思在java.sql.Date,那么它并没有真正一个字符串格式...它只是一个数字。要以特定方式对其进行格式化,请使用类似java.text.SimpleDateFormat.

Alternatively, convert it to a Joda TimeDateTime; Joda Time is a much better date and time API than the built-in one. For example, SimpleDateFormatisn't thread-safe.

或者,将其转换为Joda TimeDateTime;Joda Time 是一种比内置 API 更好的日期和时间 API。例如,SimpleDateFormat不是线程安全的。

(Note that a java.sql.Datehas more precision than a normal java.util.Date, but it looks like you don't need that here.)

(请注意, ajava.sql.Date比普通 具有更高的精度java.util.Date,但看起来您在这里不需要它。)

回答by Miquel

If it is for presentation you can use SimpleDateFormat straight away:

如果是用于演示,您可以立即使用 SimpleDateFormat:

package org.experiment;

import java.sql.Date;
import java.text.SimpleDateFormat;

public class Dates {
    private static SimpleDateFormat df = new SimpleDateFormat("MMMM yyyy");

    public static void main(String[] args){

        Date oneDate = new Date(new java.util.Date().getTime());
        System.out.println(df.format(oneDate));
    }

}

回答by Basil Bourque

tl;dr

tl;博士

myJavaSqlDate.toLocalDate()
             .format(
                 DateTimeFormatter.ofLocalizedDate ( FormatStyle.LONG )
                                  .withLocale ( Locale.UK )
             )

11 May 2017

2017 年 5 月 11 日

Do not conflate date-time values with their textual representation

不要将日期时间值与其文本表示混为一谈

As others said, a date-time object has noformat. Only strings generated from the object or parsed by the object have a format. But such strings are always separate and distinct from the date-time object.

正如其他人所说,日期时间对象没有format。只有从对象生成或由对象解析的字符串才有格式。但是这样的字符串总是与日期时间对象分开和不同的。

Use objects, not strings

使用对象,而不是字符串

Avoid using strings to communicate date-time values to/from your database. For date-time values, use date-time classes to instantiate date-time objects.

避免使用字符串与数据库之间的日期时间值进行通信。对于日期时间值,使用日期时间类来实例化日期时间对象。

The very purpose of JDBCis to mediate the differences in types between your database and Java.

JDBC的真正目的是调解数据库和 Java 之间的类型差异。

Using java.time

使用 java.time

The other Answers are outdated as they use the troublesome old legacy date-time classes or the venerable Joda-Time library. Both have been supplanted by the java.time classes.

其他答案已经过时,因为它们使用了麻烦的旧日期时间类或古老的 Joda-Time 库。两者都被 java.time 类所取代。

If you have a java.sql.Dateobject in hand, convert to java.time.LocalDateby calling the new method toLocalDateadded to the old class.

如果您java.sql.Date手头有一个对象,请java.time.LocalDate通过调用toLocalDate添加到旧类的新方法来转换为。

LocalDate ld = myJavaSqlDate.toLocalDate() ;

For JDBC driversthat comply with JDBC 4.2and later, you can work directly with java.time types.

对于符合JDBC 4.2及更高版本的JDBC 驱动程序,您可以直接使用 java.time 类型。

You seem to be interested in the date-only values. So use LocalDate. The LocalDateclass represents a date-only value without time-of-day and without time zone.

您似乎对仅日期值感兴趣。所以使用LocalDate. 该LocalDate级表示没有时间一天和不同时区的日期,唯一的价值。

To generate a string in your desired format, you could specify a custom formatting pattern. But I suggest letting java.time automatically localize.

要以所需格式生成字符串,您可以指定自定义格式模式。但我建议让 java.time 自动本地化。

To localize, specify:

要本地化,请指定:

  • FormatStyleto determine how long or abbreviated should the string be.
  • Localeto determine (a) the human language for translation of name of day, name of month, and such, and (b) the cultural norms deciding issues of abbreviation, capitalization, punctuation, separators, and such.
  • FormatStyle确定字符串的长度或缩写。
  • Locale确定 (a) 用于翻译日期名称、月份名称等的人类语言,以及 (b) 决定缩写、大写、标点符号、分隔符等问题的文化规范。

Example…

例子…

LocalDate ld = LocalDate.now ( ZoneId.of ( "America/Montreal" ) );  // Today's date at this moment in that zone.
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate ( FormatStyle.LONG ).withLocale ( Locale.UK );
String output = ld.format ( f );

output: 11 May 2017

产出:2017 年 5 月 11 日



About java.time

关于 java.time

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

java.time框架是建立在Java 8和更高版本。这些类取代了麻烦的旧的遗留日期时间类,例如java.util.Date, Calendar, & SimpleDateFormat

The Joda-Timeproject, now in maintenance mode, advises migration to the java.timeclasses.

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

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

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

Where to obtain the java.time classes?

从哪里获得 java.time 类?

The ThreeTen-Extraproject 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.

ThreeTen-额外项目与其他类扩展java.time。该项目是未来可能添加到 java.time 的试验场。你可能在这里找到一些有用的类,比如IntervalYearWeekYearQuarter,和更多