Java 时间操作
Posted 王睿丶
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java 时间操作相关的知识,希望对你有一定的参考价值。
方式一:获取时间
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH)+1;
int day = calendar.get(Calendar.DAY_OF_MONTH);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int min = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
方式二:获取格式化后的时间
public String getThisToday()
SimpleDateFormat sdf = new SimpleDateFormat("yyyy:MM:dd:HH:mm:ss");
Calendar cal = Calendar.getInstance();
String start = sdf.format(cal.getTime());
//取出具体年月日
String[] times=time.split(":");
String year = times[0];
String month = times[1];
String day = times[2];
String hour = times[3];
String min = times[4];
String second = times[5];
return start;
如果是用第一种方式获取时间,需要个位数前面补0的话,可以进行如下操作:
//这样小时和分钟就会在1位时往前补0,其他以此类推
if ((hour/10)==0)
hourS="0"+hour;
if ((min/10)==0)
minS="0"+min;
if ((second/10)==0)
secondS="0"+secondS;
获取时间戳
date2long(2022+"", 8+"", 26+"", 8+"", 1+"", 1+"")
public static long date2long(String year, String month, String day, String hour, String minutes, String sec)
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(year);
stringBuilder.append("/");
stringBuilder.append(month);
stringBuilder.append("/");
stringBuilder.append(day);
stringBuilder.append(" ");
stringBuilder.append(hour);
stringBuilder.append(":");
stringBuilder.append(minutes);
stringBuilder.append(":");
stringBuilder.append(sec);
String sDt = stringBuilder.toString();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date dt = null;
try
dt = sdf.parse(sDt);
if (dt != null)
return dt.getTime();
catch (ParseException e)
e.printStackTrace();
return -1L;
以上是关于Java 时间操作的主要内容,如果未能解决你的问题,请参考以下文章