[英]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.