java android获取相应日期的前一个日期(不是昨天的日期)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29368428/
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
android get previous date of a corresponding date(not yesterday's date)
提问by Shirish Herwade
Please read question carefully before marking duplicate.
在标记重复之前,请仔细阅读问题。
I want previous date of a correspondingdate.(Not yesterday's date)
我想要相应日期的前一个日期。(不是昨天的日期)
e.g. If user click button once he will be navigated to another screen and is shown data regarding yesterday.
例如,如果用户单击按钮一次,他将被导航到另一个屏幕并显示有关昨天的数据。
And if he clicks again the same button on that screen, then data should be shown on day before yesterday....and so on... till data present in my database.
如果他再次单击该屏幕上的相同按钮,则数据应该显示在前天....依此类推...直到数据出现在我的数据库中。
So I want to get previous date of a corresponding date. i.e. if I have date 31 Jan 2014(I'm using format 31012014 to store in db) then i should get date 30012014.
所以我想获得相应日期的前一个日期。即,如果我的日期是 2014 年 1 月 31 日(我使用格式 31012014 存储在 db 中),那么我应该得到日期 30012014。
I know how to get yesterday's date e.g. below code
我知道如何获取昨天的日期,例如下面的代码
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, -1);
DateFormat dateFormat = new SimpleDateFormat("ddMMyyyy", Locale.getDefault());
String yesterdayAsString = dateFormat.format(calendar.getTime());
which gives dates compared to today but I want previous date compared to some other valid date.
它给出了与今天相比的日期,但我想要与其他一些有效日期相比的前一个日期。
So how to get that.
那么如何获得。
回答by LaurentY
You have to use SimpleDateFormat to convert String > Date, after Date > Calendar, for instance;
例如,您必须使用 SimpleDateFormat 转换 String > Date,在 Date > Calendar 之后;
String sDate = "31012014";
SimpleDateFormat dateFormat = new SimpleDateFormat("ddMMyyyy", Locale.getDefault());
Date date = dateFormat.parse(sDate);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DATE, -1);
String yesterdayAsString = dateFormat.format(calendar.getTime());
回答by Yogendra
Use this, Its working and tested code.
使用它,它的工作和测试代码。
private String getPreviousDate(String inputDate){
inputDate = "15-12-2015"; // for example
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
try {
Date date = format.parse(inputDate);
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.DATE, -1);
inputDate = format.format(c.getTime());
Log.d("asd", "selected date : "+inputDate);
System.out.println(date);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
inputDate ="";
}
return inputDate;
}
回答by Karan Chunara
Try this one
试试这个
String prevDate;
Date c = Calendar.getInstance().getTime();
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
String todayDate=df.format(c);
Date date = null;
try {
date = df.parse(todayDate);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DATE, -1);
prevDate = df.format(calendar.getTime());
Test=(TextView)findViewById(R.id.test);
Test.setText(prevDate);
回答by Basil Bourque
tl;dr
tl;博士
Use modern java.timeclasses. Repeatedly subtract a day to move backwards in time.
使用现代java.time类。反复减去一天,时间倒退。
LocalDate // Represent a date-only value, without time-of-day and without time zone.
.now( // Determine the current date as perceived in the wall-clock time used by the people of a particular region (a time zone).
ZoneId.of( "Europe/Paris" ) // Use real time zone names in `Continent/Region` format, never 2-4 letter pseudo-zones such as PST, EST, IST, CEST, etc.
) // Returns a `LocalDate` object.
.minusDays( 1 ) // Move back in time by one day, for yesterday's date. Returns another separate `LocalDate` object rather than modify the original, per Immutable Objects pattern.
.minusDays( 1 ) // Continue moving back in time another day.
.minus(
Period.ofDays( 1 ) // Define a span-of-time as any number of years-months-weeks-days.
) // Continuing to subtract yet another day.
.toString() // Generate text representing that last generated `LocalDate` date-value using standard ISO 8601 format.
When parsing your text inputs.
解析文本输入时。
LocalDate
.parse(
"30012014" ,
DateTimeFormatter.ofPattern( "ddMMuuuu" )
)
.minusDay( 1 )
.minus(
Period.ofDays( 1 )
)
java.time
时间
The modern approach uses the java.timeclasses that years ago supplanted the troublesome old date-time classes.
现代方法使用java.time类,多年前取代了麻烦的旧日期时间类。
LocalDate
LocalDate
The LocalDate
class represents a date-only value without time-of-day and without time zoneor offset-from-UTC.
该LocalDate
级表示没有时间的天,没有一个日期,只值时区或偏移从-UTC。
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris Franceis a new day while still “yesterday” in Montréal Québec.
时区对于确定日期至关重要。对于任何给定时刻,日期因地区而异。例如,在法国巴黎午夜过后几分钟是新的一天,而在魁北克蒙特利尔仍然是“昨天” 。
If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any momentduring runtime(!), so your results may vary. Better to specify your desired/expected time zoneexplicitly as an argument.
如果未指定时区,JVM 会隐式应用其当前默认时区。该默认值可能会在运行时随时更改(!),因此您的结果可能会有所不同。最好将您想要/预期的时区明确指定为参数。
Specify a proper time zone namein the format of continent/region
, such as America/Montreal
, Africa/Casablanca
, or Pacific/Auckland
. Never use the 2-4 letter abbreviation such as EST
or IST
as they are nottrue time zones, not standardized, and not even unique(!).
以、、 或等格式指定正确的时区名称。永远不要使用 2-4 个字母的缩写,例如或因为它们不是真正的时区,不是标准化的,甚至不是唯一的(!)。continent/region
America/Montreal
Africa/Casablanca
Pacific/Auckland
EST
IST
ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalDate today = LocalDate.now( z ) ;
If you want to use the JVM's current default time zone, ask for it and pass as an argument. If omitted, the JVM's current default is applied implicitly. Better to be explicit, as the default may be changed at any moment during runtimeby any code in any thread of any app within the JVM.
如果您想使用 JVM 的当前默认时区,请询问它并作为参数传递。如果省略,则隐式应用 JVM 的当前默认值。最好是明确的,因为JVM 中任何应用程序的任何线程中的任何代码都可能在运行时随时更改默认值。
ZoneId z = ZoneId.systemDefault() ; // Get JVM's current default time zone.
Or specify a date. You may set the month by a number, with sane numbering 1-12 for January-December.
或指定日期。您可以通过数字设置月份,对于 1 月至 12 月,合理的编号为 1-12。
LocalDate ld = LocalDate.of( 1986 , 2 , 23 ) ; // Years use sane direct numbering (1986 means year 1986). Months use sane numbering, 1-12 for January-December.
Or, better, use the Month
enum objects pre-defined, one for each month of the year. Tip: Use these Month
objects throughout your codebase rather than a mere integer number to make your code more self-documenting, ensure valid values, and provide type-safety.
或者,更好的是使用Month
预定义的枚举对象,一年中的每个月一个。提示:Month
在整个代码库中使用这些对象而不仅仅是整数,以使您的代码更具自文档性、确保有效值并提供类型安全。
LocalDate ld = LocalDate.of( 1986 , Month.FEBRUARY , 23 ) ;
Date math
日期数学
Your Question is not clear, but it seems you simply want to increment backwards in time one day at a time. This is quite easy with the LocalDate
class offering plus
& minus
methods.
您的问题尚不清楚,但您似乎只是想一天一次地向后增加时间。使用LocalDate
类产品plus
和minus
方法,这很容易。
Call the convenience method, LocalDate::minusDays
.
调用便捷方法,LocalDate::minusDays
。
LocalDate yesterday = LocalDate.now( ZoneId.of( "Africa/Tunis" ) ).minusDays( 1 ) ;
To move backwards, subtract again.
要向后移动,请再次减去。
LocalDate localDatePrior = yesterday.minusDays( 1 ) ;
And continue onwards.
并继续前进。
localDatePrior = localDatePrior.minusDays( 1 ) ;
You can soft-code the period of time to subtract using the Period
class with the LocalDate.minus
method.
您可以使用Period
带有LocalDate.minus
方法的类对要减去的时间段进行软编码。
Period p = Period.ofDays( 1 ) ;
LocalDate localDatePrior = yesterday.minus( p ) ;
Database
数据库
(I'm using format 31012014 to store in db)
(我使用格式 31012014 存储在数据库中)
Don't.
别。
To store a date-only value in your database, use a date-only type in your column. In a SQL-compliant database, the type will be DATE
for a date-only value.
要在数据库中存储仅日期值,请在列中使用仅日期类型。在符合 SQL 的数据库中,该类型将DATE
用于仅日期值。
As of JDBC 4.2 we can directly exchange java.timeobjects with the database.
从 JDBC 4.2 开始,我们可以直接与数据库交换java.time对象。
myPreparedStatement.setObject( … , localDate ) ;
Retrieval.
恢复。
LocalDate localDate = myResultSet.getObject( … , LocalDate.class ) ;
Parsing
解析
But to directly address your current situation, you can parse your string with its peculiar format of DDMMYYYY.
但是要直接解决您当前的情况,您可以使用其特殊的 DDMMYYYY 格式解析您的字符串。
DateTimeFormatter f = DateTimeFormatter.ofPattern( "ddMMuuuu" ) ;
LocalDate localDate = LocalDate.parse( "30012014" , f ) ;
String output = localDate.toString() ; // Generate text in standard ISO 8601 format.
By the way, rather than invent your own date-time format, always use standard ISO 8601formats when exchanging date-time values as text. The java.timeclasses wisely use these formats by default when parsing/generating strings.
顺便说一句,在将日期时间值作为文本交换时,不要发明自己的日期时间格式,而是始终使用标准ISO 8601格式。该java.time类明智的默认解析/生成的字符串时使用这些格式。
About java.time
关于java.time
The java.timeframework is built into Java 8 and later. These classes supplant the troublesome old legacydate-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
该java.time框架是建立在Java 8和更高版本。这些类取代了麻烦的旧的遗留日期时间类,例如java.util.Date
, Calendar
, & SimpleDateFormat
。
The Joda-Timeproject, now in maintenance mode, advises migration to the java.timeclasses.
现在处于维护模式的Joda-Time项目建议迁移到java.time类。
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
要了解更多信息,请参阅Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规范是JSR 310。
You may exchange java.timeobjects directly with your database. Use a JDBC drivercompliant with JDBC 4.2or later. No need for strings, no need for java.sql.*
classes.
您可以直接与数据库交换java.time对象。使用符合JDBC 4.2或更高版本的JDBC 驱动程序。不需要字符串,不需要类。java.sql.*
Where to obtain the java.time classes?
从哪里获得 java.time 类?
- Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6and Java SE 7
- Most of the java.timefunctionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
- Later versions of Android bundle implementations of the java.timeclasses.
- For earlier Android (<26), the ThreeTenABPproject adapts ThreeTen-Backport(mentioned above). See How to use ThreeTenABP….
- Java SE 8、Java SE 9、Java SE 10、Java SE 11及更高版本 - 标准 Java API 的一部分,具有捆绑实现。
- Java 9 添加了一些小功能和修复。
- Java SE 6和Java SE 7
- 大多数java.time功能在ThreeTen-Backport 中被反向移植到 Java 6 & 7 。
- 安卓
- 更高版本的 Android 捆绑实现java.time类。
- 对于早期的 Android(<26),ThreeTenABP项目采用了ThreeTen-Backport(上面提到过)。请参阅如何使用ThreeTenABP ...。
回答by Ashwin H
Try this:
试试这个:
final Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, -1);
String yesterdayAsString = fmtOut.format(calendar.getTime());
回答by Gil Moshayof
You've got everything right, except before you "add" -1 days, you need to set it to the date you want (before finding the previous date previous):
您已经一切顺利,除了在“添加”-1 天之前,您需要将其设置为您想要的日期(在查找上一个日期之前):
Calendar calendar = Calendar.getInstance();
calendar.set(2014, Calendar.JUNE, 9);
calendar.add(Calendar.DATE, -1);
...
回答by Venelin K
First off just as a tip, it is better to store your dates as timestamps like so you won't be dependent on time formats.
首先作为提示,最好将日期存储为时间戳,这样您就不会依赖于时间格式。
As for your question, just keep your current date in a variable and send it to your method once the button is clicked and then subtract an extra day
至于您的问题,只需将您当前的日期保存在一个变量中,并在单击按钮后将其发送到您的方法,然后再减去一天
Calendar curDate = Calendar.getInstance();
curDate.add(Calendar.DATE, -1);
and use your curDate variable from then on
并从那时起使用您的 curDate 变量