
这个问题可以用两种方式得到:
方法一:在java中可以使用Date类直接获得,但是这个方法过时了,不推荐使用。
方法二:使用 javautilCalendar 类。
代码例子:
//方法1:虽然还可以用,但是已经不建议使用,已经过时。Date date = new Date();
int old_y = dategetYear()+1900;//得到年份。因为得到的是1900年后至今过了多少年,所以要加1900
int old_m = dategetMonth()+1;//因为得到的结果是0~11,故而加一。
int old_d = dategetDate();//得到月份中今天的号数
Systemoutprintln("现在是:"+old_y+"-"+old_m+"-"+old_d+"(使用过时方法)");//
//方法2:推荐使用
Calendar calendar = CalendargetInstance();
int now_y = calendarget(CalendarYEAR);//得到年份
int now_m = calendarget(CalendarMONTH)+1;//得到月份
int now_d = calendarget(CalendarDATE);//得到月份中今天的号数
int now_h = calendarget(CalendarHOUR_OF_DAY);//得到一天中现在的时间,24小时制
int now_mm = calendarget(CalendarMINUTE);//得到分钟数
int now_s = calendarget(CalendarSECOND);//得到秒数
Systemoutprintln("现在是:"+now_y+"-"+now_m+"-"+now_d+" "+now_h+":"+now_mm+":"+now_s+"(使用推荐方法)");
结果:
现在是:2015-11-9(使用过时方法)
现在是:2015-11-9 18:7:42(使用推荐方法)
获取当前时间,然后set到Calendar里边,然后从里边获取的是当前时间的东西,
如果你set的date是你自己给定的,那么获取到的就是你给定的date。
应该是时区问题,用如下代码检查下时区
DateFormat dFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");String strTime = dFormatformat(CalendargetInstance()getTime());
Systemoutprintln(strTime);
Systemoutprintln(CalendargetInstance()getTimeZone()getID());
应该显示类似
2014-04-06 16:26:06
Asia/Shanghai
Date date=new Date();
DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time=formatformat(date);
不同的方法介绍如下:
1、通过Date类来获取当前时间。
Date day=new Date()
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
Systemoutprintln(dfformat(day))
2、通过System类中的currentTimeMillis方法来获取当前时间。
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Systemoutprintln(dfformat(SystemcurrentTimeMillis()))
3、通过Calendar类来获取当前时间。
Calendar c = CalendargetInstance();//可以对每个时间域单独修改
int year = cget(CalendarYEAR)
int month = cget(CalendarMONTH)
int date = cget(CalendarDATE)
int hour = cget(CalendarHOUR_OF_DAY)
int minute = cget(CalendarMINUTE)
int second = cget(CalendarSECOND)
Systemoutprintln(year + "/" + month + "/" + date + " " +hour + ":" +minute + ":" + second)
4、通过Date类来获取当前时间。
Date date = new Date()
String year = Stringformat("%tY", date)
String month = Stringformat("%tB", date)
String day = Stringformat("%te", date)
Systemoutprintln("今天是:"+year+"-"+month+"-"+day)
以上就是关于如何用java取得年,月,日,时,分,秒全部的内容,包括:如何用java取得年,月,日,时,分,秒、在java中Calendar.HOUR_OF_DAY返回的是一个什么时间,、Calendar.getInstance()比当前系统时间晚了12小时是怎么回事等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)