Sre*_*mat 6 java date simpledateformat date-formatting
如果输入01-01-2015它应该改为2015-01-01.
如果输入2015-01-01它应该改为01-01-2015.
我使用SimpleDateFormat但没有得到正确的输出:
//Class to change date dd-MM-yyyy to yyyy-MM-dd and vice versa
public class ChangeDate {
static SimpleDateFormat formatY = new SimpleDateFormat("yyyy-MM-dd");
static SimpleDateFormat formatD = new SimpleDateFormat("dd-MM-yyyy");
//This function change dd-MM-yyyy to yyyy-MM-dd
public static String changeDtoY(String date) {
try {
return formatY.format(formatD.parse(date));
}
catch(Exception e) {
return null;
}
}
//This function change yyyy-MM-dd to dd-MM-yyyy
public static String changeYtoD(String date) {
try {
return formatD.format(formatY.parse(date));
}
catch(Exception e) {
return null;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我想要一些自动检测日期模式并更改为其他格式的条件.
有两种选择:
尝试用正则表达式检查...... 喜欢:
if (dateString.matches("\\d{4}-\\d{2}-\\d{2}")) {
...
}
Run Code Online (Sandbox Code Playgroud)尝试转换为第一个模式,如果它抛出异常,尝试转换为另一个模式(但这样做是不好的做法)
对于日期时间工作,无需担心regex。
只需尝试使用一种格式进行解析,捕获预期的异常。如果确实抛出异常,请尝试使用其他格式进行解析。如果抛出异常,那么您就知道输入意外地不是两种格式。
您正在使用旧的、麻烦的日期时间类,现在已被Java 8 及更高版本中内置的java.time框架所取代。新类的灵感来自于非常成功的Joda-Time框架,该框架旨在作为其继承者,概念相似,但经过重新架构。由JSR 310定义。由ThreeTen-Extra项目扩展。请参阅Oracle 教程。
LocalDate新类包括一个 ,LocalDate用于仅包含日期的值,不包含当天时间。正是您所需要的。
您的第一个格式可能是标准ISO 8601格式,YYYY-MM-DD。java.time 中默认使用这种格式。
如果由于输入与 ISO 8601 格式不匹配而导致第一次解析尝试失败,DateTimeParseException则会抛出 a 。
LocalDate localDate = null;
try {
localDate = LocalDate.parse( input ); // ISO 8601 formatter used implicitly.
} catch ( DateTimeParseException e ) {
// Exception means the input is not in ISO 8601 format.
}
Run Code Online (Sandbox Code Playgroud)
其他格式必须由类似于您使用 SimpleDateFormat 所做的编码模式指定。因此,如果我们从第一次尝试中捕获异常,请进行第二次解析尝试。
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "MM-dd-yyyy" );
LocalDate localDate = null;
try {
localDate = LocalDate.parse( input );
} catch ( DateTimeParseException e ) {
// Exception means the input is not in ISO 8601 format.
// Try the other expected format.
try {
localDate = LocalDate.parse( input , formatter );
} catch ( DateTimeParseException e ) {
// FIXME: Unexpected input fit neither of our expected patterns.
}
}
Run Code Online (Sandbox Code Playgroud)