Date/SimpleDateFormat/Calendar:与时间相关的一些工具类
代码实例:
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class TestSimpleDateFormat { public static void main(String[] args) throws ParseException { Date date = new Date(); //指定时间的格式(yyyy:年,MM:月,dd:日,HH:时,mm:分,ss:秒) SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); System.out.println("当前时间(格式):"+sdf.format(date)); System.out.println("--------------------"); //将文本转换为日期 String dateStr = "2016-06-10 16:47:19"; Date date2 = sdf.parse(dateStr); System.out.println("Date时间:"+date2); System.out.println("--------------------"); //Calendar类 Calendar calendar = Calendar.getInstance(); int year = calendar.get(Calendar.YEAR)+1;//0表示1月份 int month = calendar.get(Calendar.MONTH); int day = calendar.get(Calendar.DAY_OF_MONTH); int hour = calendar.get(Calendar.HOUR_OF_DAY); int minute = calendar.get(Calendar.MINUTE); int second = calendar.get(Calendar.SECOND); System.out.println("当前时间:"+year+"-"+month+"-"+day+" "+hour+":"+minute+":"+second); System.out.println("当前毫秒数:"+calendar.getTimeInMillis()); Date date3 = calendar.getTime(); System.out.println("Date时间:"+date3); System.out.println("--------------------"); } } 输出结果: 当前时间(格式):2016-06-10 17:02:54 -------------------- Date时间:Fri Jun 10 16:47:19 CST 2016 -------------------- 当前时间:2017-5-10 17:2:54 当前毫秒数:1465549374419 Date时间:Fri Jun 10 17:02:54 CST 2016 --------------------
时间: 2024-10-09 23:46:55