Java去掉时分秒
在Java中,我们经常需要处理日期和时间。有时候我们只对日期感兴趣,而不关心具体的时分秒。本文将介绍如何使用Java去掉日期中的时分秒,并提供相关的代码示例。
1. 使用java.time包
Java 8引入了新的日期和时间API,位于java.time
包中。其中,LocalDate
类表示只包含日期的对象,没有时分秒。我们可以使用该类来去掉日期中的时分秒。
import java.time.LocalDate;
import java.time.LocalDateTime;
public class RemoveTime {
public static void main(String[] args) {
LocalDateTime dateTime = LocalDateTime.now();
LocalDate date = dateTime.toLocalDate();
System.out.println("原日期时间:" + dateTime);
System.out.println("去掉时分秒后的日期:" + date);
}
}
在上面的示例中,我们首先使用LocalDateTime.now()
方法获取当前的日期和时间,然后使用toLocalDate()
方法将其转换为只包含日期的对象LocalDate
。最后,我们打印出去掉时分秒后的日期。
2. 使用Calendar类
在Java 8之前,我们可以使用Calendar
类来处理日期和时间。虽然Calendar
类有点繁琐,但我们仍然可以使用它来去掉日期中的时分秒。
import java.util.Calendar;
public class RemoveTime {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
System.out.println("去掉时分秒后的日期:" + calendar.getTime());
}
}
在上面的示例中,我们使用Calendar.getInstance()
方法获取一个Calendar
实例,然后使用set()
方法将时、分、秒和毫秒设置为0。最后,我们打印出去掉时分秒后的日期。
3. 使用SimpleDateFormat类
另一种常见的方法是使用SimpleDateFormat
类将日期格式化为不包含时分秒的字符串。
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class RemoveTime {
public static void main(String[] args) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat formatWithTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date currentDate = formatWithTime.parse(formatWithTime.format(new Date()));
System.out.println("去掉时分秒后的日期:" + format.format(currentDate));
}
}
在上面的示例中,我们首先创建了两个SimpleDateFormat
对象,一个用于格式化带有时分秒的日期时间,另一个用于格式化只包含日期的字符串。然后,我们使用format()
方法将当前日期时间格式化为带有时分秒的字符串,再使用parse()
方法将其解析为Date
对象。最后,我们使用另一个SimpleDateFormat
对象将该Date
对象格式化为只包含日期的字符串,并打印出来。
结论
通过使用java.time
包中的LocalDate
类、Calendar
类或SimpleDateFormat
类,我们可以很方便地去掉日期中的时分秒。以上是三种常见的方法,你可以根据具体的需求选择合适的方法来处理日期和时间。
流程图
flowchart TD
A(开始)
B(获取当前日期时间)
C(去掉时分秒)
D(打印去掉时分秒后的日期)
A-->B
B-->C
C-->D
D-->E(结束)
上述流程图表示了本文中介绍的方法的整体流程。首先从获取当前的日期时间开始,然后去掉时分秒,最后打印出去掉时分秒后的日期。