本文共 2270 字,大约阅读时间需要 7 分钟。
package test;import java.text.SimpleDateFormat;import java.util.Calendar;import java.util.Date;import com.sun.org.apache.xerces.internal.impl.xpath.regex.ParseException;public class DateTest { public static void main(String[] args) throws ParseException, java.text.ParseException { // 获取当前时间的Calendar对象 Calendar now = Calendar.getInstance(); System.out.println("年: " + now.get(Calendar.YEAR)); System.out.println("月: " + (now.get(Calendar.MONTH) + 1)); System.out.println("日: " + now.get(Calendar.DAY_OF_MONTH)); System.out.println("时: " + now.get(Calendar.HOUR_OF_DAY)); System.out.println("分: " + now.get(Calendar.MINUTE)); System.out.println("秒: " + now.get(Calendar.SECOND)); System.out.println("当前时间毫秒数:" + now.getTimeInMillis()); System.out.println(now.getTime()); System.out.println("************************"); // 创建一个新的Date对象 Date date = new Date(); System.out.println("当前系统时间:" + date); // 定义日期格式 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String dateFormat = sdf.format(date); System.out.println("格式化后的日期:" + dateFormat); System.out.println("************************"); // 解析指定时间字符串 String time = "2020-04-22 12:22:37"; Date moment = sdf.parse(time); System.out.println("字符串转成日期:" + moment); }} 年: 2020月: 4日: 22时: 12分: 26秒: 35当前时间毫秒数:1587529595024Wed Apr 22 12:26:35 GMT+08:00 2020************************当前系统时间:Wed Apr 22 12:26:35 GMT+08:00 2020格式化后的日期:2020-04-22 12:26:35************************字符串转成日期:Wed Apr 22 12:22:37 GMT+08:00 2020
本代码通过Java标准库中的日期处理类实现了日期信息的获取与格式化。以下是主要代码解析:
获取当前时间的Calendar对象
使用Calendar.getInstance()方法获取当前系统时间的Calendar对象。Calendar对象提供了日期和时间的各种获取方法,包括年、月、日、时、分、秒等。 日期格式化
创建一个SimpleDateFormat对象,定义日期格式为"yyyy-MM-dd HH:mm:ss"。通过format方法将Date对象转换为指定格式的字符串,方便显示和存储。 字符串解析
使用parse方法将时间字符串转换为Date对象,确保与格式化输出的一致性。 输出结果
控制台输出展示了当前系统时间、格式化后的日期以及字符串转换后的日期结果,帮助开发者验证日期处理逻辑的正确性。转载地址:http://cdhfk.baihongyu.com/