Java获取今天/昨天/前天的某个时间点的方法

Posted MikeLin麦克林

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java获取今天/昨天/前天的某个时间点的方法相关的知识,希望对你有一定的参考价值。

开发时需要把如“今天 12:15” "昨天 21:21" "前天 03: 02"之类的String转换成Date,所以写了个方法,有更好的写法的话欢迎留言

 1 //获取今天、昨天、前天的某个时间的方法, 如"昨天 21:21" "前天 15:15"
 2     private static Date getFormatDate(String updated) throws Exception{
 3         if (updated.substring(0, 2).equals("今天")){
 4             String partOfDate = updated.substring(3);
 5             Calendar calendar = Calendar.getInstance();
 6             calendar.setTime(new Date());
 7             calendar.set(Calendar.HOUR_OF_DAY, 0);
 8             calendar.set(Calendar.MINUTE, 0);
 9             calendar.set(Calendar.SECOND, 0);
10             SimpleDateFormat todaySdf = new SimpleDateFormat("yyyy-MM-dd");
11             String today = todaySdf.format(calendar.getTime());
12             String finalString = today + " " + partOfDate;
13             SimpleDateFormat finalSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
14             return finalSdf.parse(finalString);
15         }else if (updated.substring(0,2).equals("昨天")){
16             String partOfDate = updated.substring(3);
17             Calendar calendar = Calendar.getInstance();
18             calendar.setTime(new Date());
19             calendar.add(Calendar.DATE, -1);
20             calendar.set(Calendar.HOUR_OF_DAY, 0);
21             calendar.set(Calendar.MINUTE, 0);
22             calendar.set(Calendar.SECOND, 0);
23             SimpleDateFormat yesterdaySdf = new SimpleDateFormat("yyyy-MM-dd");
24             String yesterday = yesterdaySdf.format(calendar.getTime());
25             String finalString = yesterday + " " + partOfDate;
26             SimpleDateFormat finalSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
27             return finalSdf.parse(finalString);
28         }else if (updated.substring(0, 2).equals("前天")){
29             String partOfDate = updated.substring(3);
30             Calendar calendar = Calendar.getInstance();
31             calendar.setTime(new Date());
32             calendar.add(Calendar.DATE, -2);
33             calendar.set(Calendar.HOUR_OF_DAY, 0);
34             calendar.set(Calendar.MINUTE, 0);
35             calendar.set(Calendar.SECOND, 0);
36             SimpleDateFormat daysBeforeSdf = new SimpleDateFormat("yyyy-MM-dd");
37             String daysBefore = daysBeforeSdf.format(calendar.getTime());
38             String finalString = daysBefore + " " + partOfDate;
39             SimpleDateFormat finalSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
40             return finalSdf.parse(finalString);
41         }else {
42             SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
43             return sdf.parse(updated);
44         }
45     }

 

Written on Dec. 14th, 2019

以上是关于Java获取今天/昨天/前天的某个时间点的方法的主要内容,如果未能解决你的问题,请参考以下文章

js获取日期:前天,昨天,今天,明天,后天

获取昨天,前天,日期字符串

java获取昨天今天明天的日期

js获取今天明天

js获取日期:昨天今天和明天后天 [转贴记录]

java 获取今天昨天本周本月本年的时间范围的工具类