用java写一个时间格式化代码
时间: 2023-04-07 14:00:31 浏览: 78
可以的,以下是一个简单的Java时间格式化代码:
import java.text.SimpleDateFormat;
import java.util.Date;
public class TimeFormat {
public static void main(String[] args) {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = sdf.format(date);
System.out.println(formattedDate);
}
}
这个代码将当前时间格式化为"yyyy-MM-dd HH:mm:ss"的字符串,并输出到控制台。你可以根据需要修改格式化字符串。
相关问题
用java代码写一个会出现日期格式化错误的demo
好的,以下是一个会出现日期格式化错误的Java代码示例:
```java
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class DateFormattingDemo {
public static void main(String[] args) {
LocalDateTime dateTime = LocalDateTime.of(2021, 3, 17, 12, 30, 45);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyy-MM-dd HH:mm:ss");
String formattedDateTime = dateTime.format(formatter);
System.out.println(formattedDateTime);
}
}
```
在这个示例中,我们将一个 LocalDateTime 对象格式化为字符串,但是使用了错误的日期格式化字符串 "yyy-MM-dd HH:mm:ss",导致输出的字符串中年份只有三位数,而不是四位数,出现了日期格式化错误。
用Java写一个目前时间的代码
可以使用Java中的Date类和SimpleDateFormat类来获取当前时间并格式化输出,代码如下:
```java
import java.util.Date;
import java.text.SimpleDateFormat;
public class Main {
public static void main(String[] args) {
Date now = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = sdf.format(now);
System.out.println("当前时间为:" + time);
}
}
```
输出结果为:
```
当前时间为:2021-09-29 14:30:00
```