如何在java中获取上一个日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2458049/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get previous date in java
提问by Serg
I have a String Object in format yyyyMMdd.Is there a simple way to get a String with previous date in the same format? Thanks
我有一个格式为yyyyMMdd的字符串对象 。是否有一种简单的方法可以以相同的格式获取具有先前日期的字符串?谢谢
采纳答案by vkraemer
I would rewrite these answers a bit.
我会稍微改写这些答案。
You can use
您可以使用
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
// Get a Date object from the date string
Date myDate = dateFormat.parse(dateString);
// this calculation may skip a day (Standard-to-Daylight switch)...
//oneDayBefore = new Date(myDate.getTime() - (24 * 3600000));
// if the Date->time xform always places the time as YYYYMMDD 00:00:00
// this will be safer.
oneDayBefore = new Date(myDate.getTime() - 2);
String result = dateFormat.format(oneDayBefore);
To get the same results as those that are being computed by using Calendar.
获得与使用 Calendar 计算的结果相同的结果。
回答by William Witter da Silva
use SimpleDateFormat to parse the String to Date, then subtract one day. after that convert the date to String again.
使用 SimpleDateFormat 将字符串解析为日期,然后减去一天。之后再次将日期转换为字符串。
回答by brabster
It's much harder than it should be in Java without library support.
在没有库支持的情况下,这比在 Java 中应该困难得多。
You can parse the given String into a Date object using an instance of the SimpleDateFormatclass.
您可以使用SimpleDateFormat类的实例将给定的 String 解析为 Date 对象。
Then you can use Calendar's add()to subtract one day.
然后您可以使用 Calendar 的add()减去一天。
Then you can use SimpleDateFormat's format() toget the formatted date as a String.
然后您可以使用 SimpleDateFormat 的format()将格式化日期作为字符串获取。
The Joda Time librarya much easier API.
将约达时间库更容易的API。
回答by William Brendel
Here is how to do it withoutJoda Time:
这是没有Joda Time 的方法:
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class Main {
public static String previousDateString(String dateString)
throws ParseException {
// Create a date formatter using your format string
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
// Parse the given date string into a Date object.
// Note: This can throw a ParseException.
Date myDate = dateFormat.parse(dateString);
// Use the Calendar class to subtract one day
Calendar calendar = Calendar.getInstance();
calendar.setTime(myDate);
calendar.add(Calendar.DAY_OF_YEAR, -1);
// Use the date formatter to produce a formatted date string
Date previousDate = calendar.getTime();
String result = dateFormat.format(previousDate);
return result;
}
public static void main(String[] args) {
String dateString = "20100316";
try {
// This will print 20100315
System.out.println(previousDateString(dateString));
} catch (ParseException e) {
System.out.println("Invalid date string");
e.printStackTrace();
}
}
}
回答by kalyan
HI,
你好,
I want to get 20 days previous, to current date,
我想获得 20 天前到当前日期,
Calendar cal = Calendar.getInstance();
Calendar xdate = (Calendar)cal.clone();
xdate.set(Calendar.DAY_OF_YEAR, - 20);
System.out.println(" Current Time "+ cal.getTime().toString());
System.out.println(" X Time "+ xdate.getTime().toString());
I had some UN Expected result, When i tried on Jan 11th,
我有一些联合国预期的结果,当我在 1 月 11 日尝试时,
Current Time Tue Jan 11 12:32:16 IST 2011 X Time Sat Dec 11 12:32:16 IST 2010
当前时间 Tue Jan 11 12:32:16 IST 2011 X 时间 Sat Dec 11 12:32:16 IST 2010
Calendar cal = Calendar.getInstance();
Calendar xdate = (Calendar)cal.clone();
xdate.set(Calendar.DAY_OF_YEAR,cal.getTime().getDate() - 20 );
System.out.println(" Current Time "+ cal.getTime().toString());
System.out.println(" X Time "+ xdate.getTime().toString());
This code solved my Problem.
这段代码解决了我的问题。
回答by shah sanket
Calendar cal2 = Calendar.getInstance();
cal2.add(Calendar.YEAR, -1);
Date dt2 = new Date(cal2.getTimeInMillis());
System.out.println(dt2);
回答by Pratik Butani
You can use:
您可以使用:
Calendar cal = Calendar.getInstance();
//subtracting a day
cal.add(Calendar.DATE, -1);
SimpleDateFormat s = new SimpleDateFormat("yyyyMMdd");
String result = s.format(new Date(cal.getTimeInMillis()));
回答by Basil Bourque
If you are willing to use the 3rd-party utility, Joda-Time, here is some example code using Joda-Time 2.3 on Java 7. Takes just two lines.
如果您愿意使用第 3 方实用程序Joda-Time,这里有一些在 Java 7 上使用 Joda-Time 2.3 的示例代码。只需两行。
String dateAsString = "20130101";
org.joda.time.LocalDate someDay = org.joda.time.LocalDate.parse(dateAsString, org.joda.time.format.DateTimeFormat.forPattern("yyyymmdd"));
org.joda.time.LocalDate dayBefore = someDay.minusDays(1);
See the results:
查看结果:
System.out.println("someDay: " + someDay );
System.out.println("dayBefore: " + dayBefore );
When run:
运行时:
someDay: 2013-01-01
dayBefore: 2012-12-31
This code assumes you have no time zone. Lacking a time zone is rarely a good thing, but if that's your case, that code may work for you. If you do have a time zone, use a DateTimeobject instead of LocalDate.
此代码假定您没有时区。缺少时区很少是一件好事,但如果是您的情况,该代码可能适合您。如果您有时区,请使用DateTime对象而不是LocalDate。
About that example code and about Joda-Time…
关于该示例代码和 Joda-Time ......
// ? 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// Joda-Time - The popular alternative to Sun/Oracle's notoriously bad date, time, and calendar classes bundled with Java 7 and earlier.
// http://www.joda.org/joda-time/
// Joda-Time will become outmoded by the JSR 310 Date and Time API introduced in Java 8.
// JSR 310 was inspired by Joda-Time but is not directly based on it.
// http://jcp.org/en/jsr/detail?id=310
// By default, Joda-Time produces strings in the standard ISO 8601 format.
// https://en.wikipedia.org/wiki/ISO_8601
回答by kameshkr258
you can create a generic method which takes
您可以创建一个通用方法,它需要
- Date (String) (current date or from date),
- Format (String) (your desired fromat) and
- Days (number of days before(-ve value) or after(+ve value))
as input and return your desired date in required format.
作为输入并以所需格式返回所需的日期。
following method can resolve this problem.
下面的方法可以解决这个问题。
public String getRequiredDate(String date , String format ,int days){
try{
final Calendar cal = Calendar.getInstance();
cal.setTime(new SimpleDateFormat(format).parse(date));
cal.add(Calendar.DATE, days);
SimpleDateFormat sdf = new SimpleDateFormat(format);
date = sdf.format(cal.getTime());
}
catch(Exception ex){
logger.error(ex.getMessage(), ex);
}
return date;
}
}