[英]Android get date before 7 days (one week)
如何以這種格式在android中獲取一周前的日期:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
例如:現在2010-09-19 HH:mm:ss
,一周前2010-09-12 HH:mm:ss
謝謝
解析日期:
Date myDate = dateFormat.parse(dateString);
然后計算出你需要減去多少毫秒:
Date newDate = new Date(myDate.getTime() - 604800000L); // 7 * 24 * 60 * 60 * 1000
或者使用java.util.Calendar
類提供的 API:
Calendar calendar = Calendar.getInstance();
calendar.setTime(myDate);
calendar.add(Calendar.DAY_OF_YEAR, -7);
Date newDate = calendar.getTime();
然后,如果需要,將其轉換回字符串:
String date = dateFormat.format(newDate);
我創建了自己的函數,可能有助於從中獲取下一個/上一個日期
當前日期:
/**
* 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()));
}
示例:
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
如果您想通過傳遞您自己的日期來獲得計算日期:
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;
}
傳遞自己的日期的示例:
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
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 類。
LocalDate
類表示沒有時間和時區的僅日期值。
時區對於確定日期至關重要。 對於任何給定時刻,日期因地區而異。 例如,在法國巴黎午夜過后幾分鍾是新的一天,而在魁北克蒙特利爾仍然是“昨天”。
以continent/region
的格式指定正確的時區名稱,例如America/Montreal
、 Africa/Casablanca
或Pacific/Auckland
。 永遠不要使用EST
或IST
等 3-4 個字母的縮寫,因為它們不是真正的時區,不是標准化的,甚至不是唯一的(!)。
ZoneId z = ZoneId.forID( "America/Montreal" ) ;
LocalDate now = LocalDate.now ( z ) ;
使用minus…
plus…
方法做一些數學運算。
LocalDate weekAgo = now.minusWeeks( 1 );
讓 java.time 確定您所需時區的一天中的第一個時刻。 不要假設一天從00:00:00
開始。 夏令時等異常意味着一天可能從另一個時間開始,例如01:00:00
。
ZonedDateTime weekAgoStart = weekAgo.atStartOfDay( z ) ;
使用DateTimeFormatter
對象生成表示此ZonedDateTime
對象的字符串。 搜索 Stack Overflow 以獲取有關此類的更多討論。
DateTimeFormatter f = DateTimeFormatter.ISO_LOCAL_DATE_TIME ;
String output = weekAgoStart.format( f ) ;
該標准格式接近您想要的格式,但在您想要空格的中間有一個T
所以用 SPACE 代替T
。
output = output.replace( "T" , " " ) ;
java.time框架內置於 Java 8 及更高版本中。 這些類取代麻煩的老傳統日期時間類,如java.util.Date
, Calendar
,和SimpleDateFormat
。
現在處於維護模式的Joda-Time項目建議遷移到java.time類。
要了解更多信息,請參閱Oracle 教程。 並在 Stack Overflow 上搜索許多示例和解釋。 規范是JSR 310 。
從哪里獲得 java.time 類?
更新: Joda-Time 項目現在處於維護模式。 該團隊建議遷移到 java.time 類。
使用Joda-Time庫使日期時間工作變得更加容易。
請注意時區的使用。 如果省略,則您使用的是 UTC 或 JVM 的當前默認時區。
DateTime now = DateTime.now ( DateTimeZone.forID( "America/Montreal" ) ) ;
DateTime weekAgo = now.minusWeeks( 1 );
DateTime weekAgoStart = weekAgo.withTimeAtStartOfDay();
從當前日期或繞過任何日期獲取日期的一種方法
@Pratik Butani 從我們自己的日期獲取日期的第二種方法在我最后不起作用。
科特林
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))
}
爪哇
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()));
}
我可以看到兩種方式:
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");
解決方案 1 是“官方”java 方式,但使用 GregorianCalendar 可能會出現嚴重的性能問題,因此 Android 工程師添加了 android.text.format.Time 對象來解決此問題。
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());
添加 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
使用 Java 8 API 或適用於 Android 的 ThreeTenABP (minSdk<24)。
三天ABP:
implementation 'com.jakewharton.threetenabp:threetenabp:1.2.1'
'
LocalDate now= LocalDate.now();
now.minusWeeks(1);
您可以使用此代碼獲取所需的確切字符串。
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)
}
}
}
}
科特林:
import java.util.*
val Int.week: Period
get() = Period(period = Calendar.WEEK_OF_MONTH, value = this)
internal val calendar: Calendar by lazy {
Calendar.getInstance()
}
operator fun Date.minus(duration: Period): Date {
calendar.time = this
calendar.add(duration.period, -duration.value)
return calendar.time
}
data class Period(val period: Int, val value: Int)
用法:
val newDate = oldDate - 1.week
// Or val newDate = oldDate.minus(1.week)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.