如何将 java.sql.date 格式化为这种格式:“MM-dd-yyyy”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24320378/
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-14 11:31:39  来源:igfitidea点击:

How do I format a java.sql.date into this format: "MM-dd-yyyy"?

javadate

提问by Pradeep

I need to get a java.sql.date in the following format "MM-dd-yyyy", but I need it to stay a java.sql.date so I can put it into a table as date field. So, it cannot be a String after the formatting, it has to end up as a java.sql.date object.

我需要以以下格式“MM-dd-yyyy”获取 java.sql.date,但我需要它保持 java.sql.date 以便我可以将它作为日期字段放入表中。因此,它不能是格式化后的字符串,它必须以 java.sql.date 对象结束。

This is what I have tried so far:

这是我迄今为止尝试过的:

java.util.Date 
today=new Date();
String date = formatter.format(today); 
Date todaydate = formatter.parse(date);
java.sql.Date fromdate = new java.sql.Date(todaydate.getTime());
java.sql.Date todate=new java.sql.Date(todaydate.getTime()); 
String tempfromdate=formatter.format(fromdate);
String temptodate=formatter.format(todate); 
java.sql.Date fromdate1=(java.sql.Date) formatter.parse(tempfromdate); 
java.sql.Date todate1=(java.sql.Date) formatter.parse(temptodate);

回答by Nirav Prajapati

Use below code i have convert today date. learn from it and try with your code

使用下面的代码我已经转换了今天的日期。从中学习并尝试使用您的代码

          Date today = new Date();

        //If you print Date, you will get un formatted output
        System.out.println("Today is : " + today);

        //formatting date in Java using SimpleDateFormat
        SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("MM-dd-yyyy");
        String date = DATE_FORMAT.format(today);
        System.out.println("Today in MM-dd-yyyy format : " + date);

            Date date1 = formatter.parse(date);
    System.out.println(date1);
    System.out.println(formatter.format(date1));

回答by Elliott Frisch

You can do it the same way as a java.util.Date(since java.sql.Dateis a sub-class of java.util.Date) with a SimpleDateFormat

您可以像 a java.util.Date(因为java.sql.Date是 的子类java.util.Date)一样使用 aSimpleDateFormat

SimpleDateFormat sdf = new SimpleDateFormat(
    "MM-dd-yyyy");
int year = 2014;
int month = 10;
int day = 31;
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month - 1); // <-- months start
                                    // at 0.
cal.set(Calendar.DAY_OF_MONTH, day);

java.sql.Date date = new java.sql.Date(cal.getTimeInMillis());
System.out.println(sdf.format(date));

Output is the expected

输出是预期的

10-31-2014

10-31-2014

回答by Varun Achar

A simpler solution would be to just convert the date in the query to epoch before comparing.

一个更简单的解决方案是在比较之前将查询中的日期转换为纪元。

SELECT date_column from YourTable where UNIX_TIMESTAMP(date_column) > ?;

Then, simply pass date.getTime()when binding value to ?.

然后,date.getTime()在将值绑定到?.

NOTE: The UNIX_TIMESTAMPfunction is for MySQL. You'll find such functions for other databases too.

注意:该UNIX_TIMESTAMP功能适用于 MySQL。您也会在其他数据库中找到此类函数。

回答by Scary Wombat

The formatter.parsewill only give you a java.util.Datenot a java.sql.Date

formatter.parse只会给你一个java.util.Datejava.sql.Date

once you have a java.util.Dateyou can convert it to a java.sql.Dateby doing

一旦你有一个java.util.Date你可以java.sql.Date通过做将它转换为

java.sql.Date sqlDate = new java.sql.Date (normalDate.getTime ());

Also note that nodates have any built in format, it is in reality a class built on top of a number.

另外请注意,没有日期,已建的任何格式,它实际上是建立在一些顶级的类。

回答by Mustafa sabir

java.util.Date today=new Date();
java.sql.Date date=new java.sql.Date(today.getTime()); //your SQL date object
SimpleDateFormat simpDate = new SimpleDateFormat("MM-dd-yyyy");
System.out.println(simpDate.format(date)); //output String in MM-dd-yyyy

Note that it does not matter if your date is in format mm-dd-yyyy or any other format, when you compare date (java.sql.Date or java.util.Date) they will always be compared in form of the dates they represent. The format of date is just a way of setting or getting date in desired format.

请注意,日期是 mm-dd-yyyy 格式还是任何其他格式都没有关系,当您比较日期(java.sql.Date 或 java.util.Date)时,它们将始终以日期的形式进行比较代表。日期格式只是以所需格式设置或获取日期的一种方式。

回答by Ole V.V.

For anyone reading this in 2017 or later, the modern solution uses LocalDatefrom java.time, the modern Java date and time API, instead of java.sql.Date. The latter is long outdated.

对于在 2017 年或以后阅读本文的任何人,现代解决方案使用LocalDatefrom java.time,现代 Java 日期和时间 API,而不是java.sql.Date. 后者早已过时。

Formatting your date

格式化你的日期

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd-uuuu", Locale.US);
    LocalDate fromDate = LocalDate.now(ZoneId.of("Asia/Kolkata"));
    String tempFromDate = fromDate.format(formatter);
    System.out.println(tempFromDate);

This prints something like

这会打印出类似的东西

11-25-2017

Don't confuse your date value with its textual representation

不要将日期值与其文本表示混淆

Neither a LocalDatenor a java.sql.Dateobject has any inherent format. So please try — and try hard if necessary — to keep the two concepts apart, the date on one side and its presentation to a user on the other.

aLocalDatejava.sql.Dateobject 都没有任何固有格式。所以请尝试——并在必要时努力——将两个概念分开,一方面是日期,另一方面是向用户展示。

It's like intand all other data types. An intcan have a value of 4284. You may format this into 4,284 or 4 284, 004284 or even into hex representation. This does in no way alter the intitself. In the same way, formatting your date does not affect your date object. So use the string for presenting to the user, and use LocalDatefor storing into your database (a modern JDBC driver or other modern means of database access wil be happy to do that, for example through PreparedStatement.setObject()).

它就像int和所有其他数据类型一样。Anint的值可以为 4284。您可以将其格式化为 4,284 或 4 284、004284 甚至十六进制表示。这绝不会改变它int本身。同样,格式化您的日期不会影响您的日期对象。因此,将字符串用于呈现给用户,并LocalDate用于存储到您的数据库中(现代 JDBC 驱动程序或其他现代数据库访问方式将很乐意这样做,例如通过PreparedStatement.setObject())。

Use explicit time zone

使用明确的时区

Getting today's date is a time zone sensitive operation since it is not the same date in all time zones of the world. I strongly recommend you make this fact explicit in the code. In my snippet I have used Asia/Kolkata time zone, please substitute your desired time zone. You mayuse ZoneId.systemDefault()for your JVM's time zone setting, but please be aware that this setting may be changed under our feet by other parts of your program or other programs running in the same JVM, so this is fragile.

获取今天的日期是对时区敏感的操作,因为它在世界上的所有时区都不是相同的日期。我强烈建议您在代码中明确说明这一事实。在我的片段中,我使用了亚洲/加尔各答时区,请替换您想要的时区。您可以使用ZoneId.systemDefault()JVM 的时区设置,但请注意,您的程序的其他部分或在同一 JVM 中运行的其他程序可能会更改此设置,因此这很脆弱。