Java获取时间年、月、日的方法
程序员文章站
2024-03-04 20:22:36
本文实例讲述了java获取时间年、月、日的方法。分享给大家供大家参考。具体实现方法如下:
package com.date.demo;
import java...
本文实例讲述了java获取时间年、月、日的方法。分享给大家供大家参考。具体实现方法如下:
package com.date.demo; import java.text.parseexception; import java.text.simpledateformat; import java.util.calendar; import java.util.date; public class datedemo { public static void main(string args[]) { system.out.println("---------------获取当前时间的年月日-----------------"); getmonthday(); system.out.println("---------------获取自定义时间的年月日-----------------"); getmonthday2set(); } /** * 获取自定义时间的年月日 */ private static void getmonthday2set() { string datestr = "2013-11-10 18:45:39"; simpledateformat sdf = new simpledateformat("yyyy-mm-dd hh:mm:ss"); calendar cal = calendar.getinstance(); date dt = null; try { dt = sdf.parse(datestr); cal.settime(dt); } catch (parseexception e) { // todo auto-generated catch block e.printstacktrace(); } int year = cal.get(calendar.year); int month = cal.get(calendar.month) + 1; int day = cal.get(calendar.day_of_month); int hour = cal.get(calendar.hour_of_day); int minute = cal.get(calendar.minute); int second = cal.get(calendar.second); system.out.println("===年===" + year); system.out.println("===月===" + month); system.out.println("===日===" + day); system.out.println("===时===" + hour); system.out.println("===分===" + minute); system.out.println("===秒===" + second); } /** * 获取当前时间的年月日 */ private static void getmonthday() { calendar cal = calendar.getinstance(); int year = cal.get(calendar.year); int month = cal.get(calendar.month) + 1; int day = cal.get(calendar.day_of_month); int hour = cal.get(calendar.hour_of_day); int minute = cal.get(calendar.minute); int second = cal.get(calendar.second); system.out.println("===年===" + year); system.out.println("===月===" + month); system.out.println("===日===" + day); system.out.println("===时===" + hour); system.out.println("===分===" + minute); system.out.println("===秒===" + second); } }
希望本文所述对大家的java程序设计有所帮助。