[英]Converting MySQL date format in Java
I am touching Java for the very first time here, so go easy on me. 我在这里第一次接触Java,所以对我很轻松。 I am having to correct someone else's older code.
我不得不纠正别人的旧代码。 This java program takes data from a MySQL table and prepares it for presentation on web pages.
这个java程序从MySQL表中获取数据并准备在网页上进行演示。 I found that their MySQL table for some reason used INT fields for all the dates.
我发现他们的MySQL表由于某种原因在所有日期都使用了INT字段。 So, for instance, today's date is stored as the INT 3222017. I first had to add the proper DATE columns to the MySQL table.
因此,例如,今天的日期存储为INT 3222017.我首先必须将正确的DATE列添加到MySQL表中。 Next I re-did another Java script to pull the data from a larger table for the MySQL table that this script will be using.
接下来,我重新做了另一个Java脚本,从这个脚本将使用的MySQL表的较大表中提取数据。
Now I need to change the code that currently formats the INT fields into MM/dd/yyyy to instead take the DATE fields (stored as yyyy-MM-dd) and convert them to the same MM/dd/yyyy. 现在我需要将当前格式化INT字段的代码更改为MM / dd / yyyy,而不是使用DATE字段(存储为yyyy-MM-dd)并将它们转换为相同的MM / dd / yyyy。
Here is a piece of the code that uses the function dateFormat on the INT fields - 这是在INT字段上使用函数dateFormat的代码片段 -
String formattedDate = "";
formattedDate = dateFormat(oneSpectro.getSpectroLastDate());
result.setSpectroLastDate(formattedDate);
formattedDate = dateFormat(oneSpectro.getSpectroOrigDate());
result.setSpectroOrigDate(formattedDate);
formattedDate = dateFormat(oneSpectro.getSpectroCalDate());
result.setSpectroCalDate(formattedDate);
}
return result;
}
And here is the dateFormat function - 这是dateFormat函数 -
public String dateFormat(int theDate){
String dateString = "";
Integer dateInt = 0;
if (theDate < 10000000){
dateInt = new Integer(theDate);
dateString = dateInt.toString();
// Add preceding 0 to make the date 8 digits in length.
dateString = "0" + dateString;
}
else {
// Process an 8 digit date.
dateInt = new Integer(theDate);
dateString = dateInt.toString();
}
// Install date slashes in the date string.
if (dateString.length() == 8){
dateString = dateString.substring(0, 2) + "/" + dateString.substring(2, 4) + "/"
+ dateString.substring(4);
}
return dateString;
}
How do I go about converting a DATE field (yyyy-MM-dd) to a formatted date of MM/dd/yyyy? 如何将DATE字段(yyyy-MM-dd)转换为格式化日期MM / dd / yyyy?
You can convert String to Date util: 您可以将String转换为Date util:
DateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
Date date = format.parse(your string);
And then convert the Date object to your String format: 然后将Date对象转换为String格式:
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
String result = df.format(date);
LocalDate.parse( // Use modern java.time classes rather than troublesome legacy date-time classes
String.format("%08d", 3222017) , // Let Java pad with leading zero.
DateTimeFormatter.ofPattern( "MMdduuuu" ) // Parse string as a `LocalDate`.
)
2017-03-22
2017年3月22日
DATE
column type DATE
列类型 That is one ridiculously bad way to store a date value. 这是存储日期值的一种非常糟糕的方法。
When storing date data, one should use a date datatype when defining the database column. 存储日期数据时,应在定义数据库列时使用日期数据类型。
You should not be using integers nor strings for moving this data in and out of your database. 您不应该使用整数或字符串来将数据移入和移出数据库。 Let your JDBC driver do its job , transmitting
java.time.LocalDate
objects to/from your database's column defined as a date datatype. 让您的JDBC驱动程序完成其工作 ,将
java.time.LocalDate
对象传输到数据库的列,该列定义为日期数据类型。 In MySQL that would be the DATE
type . 在MySQL中,它将是
DATE
类型 。
If your JDBC driver complies with JDBC 4.2 or later, use the PreparedStatement::setObject
and ResultSet::getObject
methods to pass & get a java.time.LocalDate
object. 如果JDBC驱动程序符合JDBC 4.2或更高版本,请使用
PreparedStatement::setObject
和ResultSet::getObject
方法传递和获取java.time.LocalDate
对象。 For older drivers, convert the java.time types to the legacy java.sql types such as java.sql.Date
. 对于较旧的驱动程序,将java.time类型转换为旧的java.sql类型,例如
java.sql.Date
。 Look for new methods added to the old classes for conversion. 寻找添加到旧类进行转换的新方法。
java.sql.Date sqlDate = java.sql.Date.valueOf( myLocalDate );
Going the other direction. 走向另一个方向。
LocalDate localDate = myJavaSqlDate.toLocalDate();
The other Answers use the troublesome old legacy date-time classes. 其他答案使用麻烦的旧遗留日期时间类。 Those are now legacy, supplanted by the java.time classes.
这些现在已经遗留下来,取而代之的是java.time类。
The LocalDate
class represents a date-only value without time-of-day and without time zone. LocalDate
类表示没有时间且没有时区的仅日期值。
The format YYYY-MM-DD for dates is defined in the ISO 8601 standard. 日期格式YYYY-MM-DD在ISO 8601标准中定义。 The java.time classes use the standard formats by default.
默认情况下,java.time类使用标准格式。 So no need to specify a formatting pattern.
因此无需指定格式化模式。
LocalDate localDate = LocalDate.parse( "2017-03-22" );
To parse your funky pseudo-integer string, define a formatting pattern to match. 要解析时髦的伪整数字符串,请定义要匹配的格式设置模式。
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MMdduuuu" );
To generate that string from the integer, you can shorten that existing code of yours by letting Java pad with leading zero . 要从整数生成该字符串,您可以通过让Java填充为前导零来缩短您现有的代码。
String input = String.format("%08d", 3222017) ;
03222017
03222017
Parse that input using the DateTimeFormatter
to produce a LocalDate
object. 使用
DateTimeFormatter
解析该输入以生成LocalDate
对象。
LocalDate localDate = LocalDate.parse( input , f );
localDate.toString(): 2017-03-22
localDate.toString():2017-03-22
See this code run live at IdeOne.com . 请参阅IdeOne.com上的此代码 。
The java.time framework is built into Java 8 and later. java.time框架内置于Java 8及更高版本中。 These classes supplant the troublesome old legacy date-time classes such as
java.util.Date
, Calendar
, & SimpleDateFormat
. 这些类取代了麻烦的旧遗留日期时间类,如
java.util.Date
, Calendar
和SimpleDateFormat
。
The Joda-Time project, now in maintenance mode , advises migration to the java.time classes. 现在处于维护模式的Joda-Time项目建议迁移到java.time类。
To learn more, see the Oracle Tutorial . 要了解更多信息,请参阅Oracle教程 。 And search Stack Overflow for many examples and explanations.
并搜索Stack Overflow以获取许多示例和解释。 Specification is JSR 310 .
规范是JSR 310 。
Where to obtain the java.time classes? 从哪里获取java.time类?
The ThreeTen-Extra project extends java.time with additional classes. ThreeTen-Extra项目使用其他类扩展了java.time。 This project is a proving ground for possible future additions to java.time.
该项目是未来可能添加到java.time的试验场。 You may find some useful classes here such as
Interval
, YearWeek
, YearQuarter
, and more . 您可以在这里找到一些有用的类,比如
Interval
, YearWeek
, YearQuarter
,和更多 。
try {
String dateString = "2017-03-22";
// convert string to date
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
Date date = f.parse(dateString);
// change the date format
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
String result = df.format(date);
} catch(ParseException e) {
throw new RuntimeException(e);
}
Joao's solution works. Joao的解决方案有效。 A few gotchas:
一些陷阱:
I hope this helps. 我希望这有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.