因工作需要处理时间,记录下来,以便以后使用。
package time;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class TimeHuan {
/**
* @return 返回给定格式的当前日期
*/
public String newtime(){
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
String time=df.format(new Date());
return time;
}
/**
* 将字符串格式存储的时间转为date类型
* @param date 要操作的字符串
* @return
* @throws ParseException
*/
public Date testTime(String date) throws ParseException{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date d=sdf.parse(date);
return d;
}
/**
* 判断给定时间是今天、昨天、更早。
* @param createTime 要判断的时间
* @return
*/
public String parseDate(String createTime){
try {
String ret = "";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long create = sdf.parse(createTime).getTime();
Calendar now = Calendar.getInstance();
long ms = 1000*(now.get(Calendar.HOUR_OF_DAY)*3600+now.get(Calendar.MINUTE)*60+now.get(Calendar.SECOND));//毫秒数
long ms_now = now.getTimeInMillis();
if(ms_now-create<ms){
ret = "今天";
}else if(ms_now-create<(ms+24*3600*1000)){
ret = "昨天";
}else if(ms_now-create<(ms+24*3600*1000*2)){
ret = "前天";
}else{
ret= "更早";
}
return ret;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* @return 输出昨天
*/
public String yesterday(){
Date as = new Date(new Date().getTime()-24*60*60*1000);
SimpleDateFormat matter1 = new SimpleDateFormat("yyyy-MM-dd");
String times = matter1.format(as);
System.out.println(times);
return times;
}
//main主方法
public static void main(String[] args) throws ParseException {
TimeHuan time=new TimeHuan();
Date nowdate=new Date();
String myString="2015-05-14 12:54:23";
String result=time.parseDate(myString);
System.out.println(result);
}
}
- 部分参考:
- http://blog.csdn.net/jspamd/article/details/17716461