Java Android 在 7 天(一周)之前获取日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3747490/
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 date before 7 days (one week)
提问by Jovan
How to get date before one week from now in android in this format:
如何以这种格式在android中获取一周前的日期:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
ex: now 2010-09-19 HH:mm:ss
, before one week 2010-09-12 HH:mm:ss
例如:现在2010-09-19 HH:mm:ss
,一周前2010-09-12 HH:mm:ss
Thanks
谢谢
采纳答案by Dan Dyer
Parse the date:
解析日期:
Date myDate = dateFormat.parse(dateString);
And then either figure out how many milliseconds you need to subtract:
然后计算出你需要减去多少毫秒:
Date newDate = new Date(myDate.getTime() - 604800000L); // 7 * 24 * 60 * 60 * 1000
Or use the API provided by the java.util.Calendar
class:
或者使用java.util.Calendar
类提供的API :
Calendar calendar = Calendar.getInstance();
calendar.setTime(myDate);
calendar.add(Calendar.DAY_OF_YEAR, -7);
Date newDate = calendar.getTime();
Then, if you need to, convert it back to a String:
然后,如果需要,将其转换回字符串:
String date = dateFormat.format(newDate);
回答by Kevin Gaudin
I can see two ways:
我可以看到两种方式:
Use a GregorianCalendar:
Calendar someDate = GregorianCalendar.getInstance(); someDate.add(Calendar.DAY_OF_YEAR, -7); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String formattedDate = dateFormat.format(someDate);
Use a android.text.format.Time:
long yourDateMillis = System.currentTimeMillis() - (7 * 24 * 60 * 60 * 1000); Time yourDate = new Time(); yourDate.set(yourDateMillis); String formattedDate = yourDate.format("%Y-%m-%d %H:%M:%S");
Calendar someDate = GregorianCalendar.getInstance(); someDate.add(Calendar.DAY_OF_YEAR, -7); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String formattedDate = dateFormat.format(someDate);
long yourDateMillis = System.currentTimeMillis() - (7 * 24 * 60 * 60 * 1000); Time yourDate = new Time(); yourDate.set(yourDateMillis); String formattedDate = yourDate.format("%Y-%m-%d %H:%M:%S");
Solution 1 is the "official" java way, but using a GregorianCalendar can have serious performance issues so Android engineers have added the android.text.format.Time object to fix this.
解决方案 1 是“官方”java 方式,但使用 GregorianCalendar 可能会出现严重的性能问题,因此 Android 工程师添加了 android.text.format.Time 对象来解决此问题。
回答by Pratik Butani
I have created my own function that may helpful to get Next/Previous date from
我创建了自己的函数,可能有助于从中获取下一个/上一个日期
Current Date:
当前的日期:
/**
* Pass your date format and no of days for minus from current
* If you want to get previous date then pass days with minus sign
* else you can pass as it is for next date
* @param dateFormat
* @param days
* @return Calculated Date
*/
public static String getCalculatedDate(String dateFormat, int days) {
Calendar cal = Calendar.getInstance();
SimpleDateFormat s = new SimpleDateFormat(dateFormat);
cal.add(Calendar.DAY_OF_YEAR, days);
return s.format(new Date(cal.getTimeInMillis()));
}
Example:
例子:
getCalculatedDate("dd-MM-yyyy", -10); // It will gives you date before 10 days from current date
getCalculatedDate("dd-MM-yyyy", 10); // It will gives you date after 10 days from current date
and if you want to get Calculated Date with passing Your own date:
如果您想通过传递您自己的日期来获得计算日期:
public static String getCalculatedDate(String date, String dateFormat, int days) {
Calendar cal = Calendar.getInstance();
SimpleDateFormat s = new SimpleDateFormat(dateFormat);
cal.add(Calendar.DAY_OF_YEAR, days);
try {
return s.format(new Date(s.parse(date).getTime()));
} catch (ParseException e) {
// TODO Auto-generated catch block
Log.e("TAG", "Error in Parsing Date : " + e.getMessage());
}
return null;
}
Example with Passing own date:
传递自己的日期的示例:
getCalculatedDate("01-01-2015", "dd-MM-yyyy", -10); // It will gives you date before 10 days from given date
getCalculatedDate("01-01-2015", "dd-MM-yyyy", 10); // It will gives you date after 10 days from given date
回答by Basil Bourque
tl;dr
tl;博士
LocalDate
.now( ZoneId.of( "Pacific/Auckland" ) ) // Get the date-only value for the current moment in a specified time zone.
.minusWeeks( 1 ) // Go back in time one week.
.atStartOfDay( ZoneId.of( "Pacific/Auckland" ) ) // Determine the first moment of the day for that date in the specified time zone.
.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME ) // Generate a string in standard ISO 8601 format.
.replace( "T" , " " ) // Replace the standard "T" separating date portion from time-of-day portion with a SPACE character.
java.time
时间
The modern approach uses the java.time classes.
现代方法使用 java.time 类。
The LocalDate
class represents a date-only value without time-of-day and without time zone.
该LocalDate
级表示没有时间一天和不同时区的日期,唯一的价值。
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.
时区对于确定日期至关重要。对于任何给定时刻,日期因地区而异。例如,在法国巴黎午夜过后几分钟是新的一天,而在魁北克蒙特利尔仍然是“昨天” 。
Specify a proper time zone namein the format of continent/region
, such as America/Montreal
, Africa/Casablanca
, or Pacific/Auckland
. Never use the 3-4 letter abbreviation such as EST
or IST
as they are nottrue time zones, not standardized, and not even unique(!).
以、、 或等格式指定正确的时区名称。永远不要使用 3-4 个字母的缩写,例如或因为它们不是真正的时区,不是标准化的,甚至不是唯一的(!)。continent/region
America/Montreal
Africa/Casablanca
Pacific/Auckland
EST
IST
ZoneId z = ZoneId.forID( "America/Montreal" ) ;
LocalDate now = LocalDate.now ( z ) ;
Do some math using the minus…
and plus…
methods.
使用minus…
和plus…
方法做一些数学运算。
LocalDate weekAgo = now.minusWeeks( 1 );
Let java.time determine the first moment of the day for your desired time zone. Do not assume the day starts at 00:00:00
. Anomalies such as Daylight Saving Time means the day may start at another time-of-day such as 01:00:00
.
让 java.time 确定您所需时区的一天中的第一个时刻。不要假设一天从 开始00:00:00
。夏令时等异常意味着一天可能从另一个时间开始,例如01:00:00
。
ZonedDateTime weekAgoStart = weekAgo.atStartOfDay( z ) ;
Generate a string representing this ZonedDateTime
object using a DateTimeFormatter
object. Search Stack Overflow for many more discussions on this class.
ZonedDateTime
使用DateTimeFormatter
对象生成表示此对象的字符串。搜索 Stack Overflow 以获取有关此类的更多讨论。
DateTimeFormatter f = DateTimeFormatter.ISO_LOCAL_DATE_TIME ;
String output = weekAgoStart.format( f ) ;
That standard format is close to what you want, but has a T
in the middle where you want a SPACE. So substitute SPACE for T
.
该标准格式与您想要的很接近,但T
在您想要空格的中间有一个。因此,将 SPACE 替换为T
.
output = output.replace( "T" , " " ) ;
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。
Where to obtain the java.time classes?
从哪里获得 java.time 类?
- Java SE 8, Java SE 9, and later
- Built-in.
- Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6and Java SE 7
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
- The ThreeTenABPproject adapts ThreeTen-Backport(mentioned above) for Android specifically.
- See How to use ThreeTenABP….
- Java SE 8、Java SE 9及更高版本
- 内置。
- 具有捆绑实现的标准 Java API 的一部分。
- Java 9 添加了一些小功能和修复。
- Java SE 6和Java SE 7
- 多的java.time功能后移植到Java 6和7在ThreeTen-反向移植。
- 安卓
- 所述ThreeTenABP项目适应ThreeTen-反向移植(上述)为Android特异性。
- 请参阅如何使用ThreeTenABP ...。
Joda-Time
乔达时间
Update:The Joda-Time project is now in maintenance mode. The team advises migration to the java.time classes.
更新:Joda-Time 项目现在处于维护模式。该团队建议迁移到 java.time 类。
Using the Joda-Timelibrary makes date-time work much easier.
使用Joda-Time库使日期时间工作变得更加容易。
Note the use of a time zone. If omitted, you are working in UTC or the JVM's current default time zone.
请注意时区的使用。如果省略,则您使用的是 UTC 或 JVM 的当前默认时区。
DateTime now = DateTime.now ( DateTimeZone.forID( "America/Montreal" ) ) ;
DateTime weekAgo = now.minusWeeks( 1 );
DateTime weekAgoStart = weekAgo.withTimeAtStartOfDay();
回答by Islam Assi
public static Date getDateWithOffset(int offset, Date date){
Calendar calendar = calendar = Calendar.getInstance();;
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_MONTH, offset);
return calendar.getTime();
}
Date weekAgoDate = getDateWithOffset(-7, new Date());
OR using Joda:
或使用乔达:
add Joda library
添加 Joda 库
implementation 'joda-time:joda-time:2.10'
'
'
DateTime now = new DateTime();
DateTime weekAgo = now.minusWeeks(1);
Date weekAgoDate = weekAgo.toDate()// if you want to convert it to Date
-----------------------------UPDATE-------------------------------
- - - - - - - - - - - - - - -更新 - - - - - - - - - - -----------
Use Java 8 APIs or ThreeTenABP for Android (minSdk<24).
使用 Java 8 API 或适用于 Android 的 ThreeTenABP (minSdk<24)。
ThreeTenABP:
三天ABP:
implementation 'com.jakewharton.threetenabp:threetenabp:1.2.1'
'
'
LocalDate now= LocalDate.now();
now.minusWeeks(1);
回答by Prashant Jajal
You can use this code for get exact string which you want.
您可以使用此代码获取所需的确切字符串。
object DateUtil{
fun timeAgo(context: Context, time_ago: Long): String {
val curTime = Calendar.getInstance().timeInMillis / 1000
val timeElapsed = curTime - (time_ago / 1000)
val minutes = (timeElapsed / 60).toFloat().roundToInt()
val hours = (timeElapsed / 3600).toFloat().roundToInt()
val days = (timeElapsed / 86400).toFloat().roundToInt()
val weeks = (timeElapsed / 604800).toFloat().roundToInt()
val months = (timeElapsed / 2600640).toFloat().roundToInt()
val years = (timeElapsed / 31207680).toFloat().roundToInt()
// Seconds
return when {
timeElapsed <= 60 -> context.getString(R.string.just_now)
minutes <= 60 -> when (minutes) {
1 -> context.getString(R.string.x_minute_ago, minutes)
else -> context.getString(R.string.x_minute_ago, minutes)
}
hours <= 24 -> when (hours) {
1 -> context.getString(R.string.x_hour_ago, hours)
else -> context.getString(R.string.x_hours_ago, hours)
}
days <= 7 -> when (days) {
1 -> context.getString(R.string.yesterday)
else -> context.getString(R.string.x_days_ago, days)
}
weeks <= 4.3 -> when (weeks) {
1 -> context.getString(R.string.x_week_ago, weeks)
else -> context.getString(R.string.x_weeks_ago, weeks)
}
months <= 12 -> when (months) {
1 -> context.getString(R.string.x_month_ago, months)
else -> context.getString(R.string.x_months_ago, months)
}
else -> when (years) {
1 -> context.getString(R.string.x_year_ago, years)
else -> context.getString(R.string.x_years_ago, years)
}
}
}
}
回答by Sunil
Try this
尝试这个
One single method for getting the date from current or bypassing any date
从当前日期或绕过任何日期获取日期的一种方法
@Pratik Butani's second method for getting the date from our own date is not working at my end.
@Pratik Butani 从我们自己的日期获取日期的第二种方法在我最后不起作用。
Kotlin
科特林
fun getCalculatedDate(date: String, dateFormat: String, days: Int): String {
val cal = Calendar.getInstance()
val s = SimpleDateFormat(dateFormat)
if (date.isNotEmpty()) {
cal.time = s.parse(date)
}
cal.add(Calendar.DAY_OF_YEAR, days)
return s.format(Date(cal.timeInMillis))
}
Java
爪哇
public static String getCalculatedDate(String date,String dateFormat, int days) {
Calendar cal = Calendar.getInstance();
SimpleDateFormat s = new SimpleDateFormat(dateFormat);
if (!date.isEmpty()) {
try {
cal.setTime(s.parse(date));
} catch (ParseException e) {
e.printStackTrace();
}
}
cal.add(Calendar.DAY_OF_YEAR, days);
return s.format(new Date(cal.getTimeInMillis()));
}
Usage
用法
- getCalculatedDate("", "yyyy-MM-dd", -2) // If you want date from today
- getCalculatedDate("2019-11-05", "yyyy-MM-dd", -2) // If you want date from your own
- getCalculatedDate("", "yyyy-MM-dd", -2) // 如果你想要今天的日期
- getCalculatedDate("2019-11-05", "yyyy-MM-dd", -2) // 如果你想要你自己的日期