判断字符串是否可以转成yyyy-MM-dd HH:mm:ss
时间: 2024-06-20 11:03:54 浏览: 14
可以通过以下代码判断一个字符串是否可以转成yyyy-MM-dd HH:mm:ss格式的日期时间:
```
import java.text.SimpleDateFormat;
public class DateUtil {
public static boolean isValidDateTime(String dateTimeStr) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
format.setLenient(false);
format.parse(dateTimeStr);
return true;
} catch (Exception e) {
return false;
}
}
}
```
该方法将会返回一个布尔值,如果传入的字符串符合yyyy-MM-dd HH:mm:ss格式则返回true,否则返回false。
相关问题
Java判断判断字符串是否是yyyy-MM-dd HH:mm:ss还是yyyy-MM-dd HH:mm 都统一转成yyyy-MM-dd HH:mm
好的,您可以使用Java中的SimpleDateFormat类来实现该需求。可以先将字符串转换成Date类型,再将其转换为需要的格式。下面是示例代码:
```
String str = "2022-07-12 15:30";
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
try {
// 将字符串转换成Date类型
Date date = format1.parse(str);
// 将Date类型转换成需要的格式
String result = format2.format(date);
System.out.println(result);
} catch (ParseException e) {
e.printStackTrace();
}
```
此代码先将字符串按照"yyyy-MM-dd HH:mm:ss"的格式转换成Date类型,然后再按照"yyyy-MM-dd HH:mm"的格式转换成所需的字符串格式。如果字符串是"yyyy-MM-dd HH:mm"的格式,也可以先按照这个格式转换成Date类型,再按照需要的格式转换即可。
用jdk1.8的方法判断字符串是否是yyyy-MM-dd HH:mm:ss还是yyyy-MM-dd HH:mm 都统一转成yyyy-MM-dd HH:mm
可以使用正则表达式来判断字符串是否符合指定的格式。具体实现如下:
```java
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormatTest {
public static void main(String[] args) {
String pattern = "yyyy-MM-dd HH:mm";
String dateString = "2022-01-01 12:00:00";
// 判断字符串是否符合 yyyy-MM-dd HH:mm:ss 格式
if (dateString.matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}")) {
pattern = "yyyy-MM-dd HH:mm:ss";
}
SimpleDateFormat inputFormat = new SimpleDateFormat(pattern);
SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
try {
Date date = inputFormat.parse(dateString);
String outputString = outputFormat.format(date);
System.out.println(outputString);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
```
首先定义默认格式为 yyyy-MM-dd HH:mm,然后判断字符串是否符合 yyyy-MM-dd HH:mm:ss 格式,如果符合则更新格式为 yyyy-MM-dd HH:mm:ss。
接着使用 SimpleDateFormat 类将字符串解析为 Date 对象,再将 Date 对象按照默认格式转换为字符串输出。