【问题标题】:Android get date before 7 days (one week)Android 获取日期前 7 天(一周)
【发布时间】:2011-04-14 10:23:27
【问题描述】:

如何以这种格式在android中获取一周前的日期:

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

例如:现在2010-09-19 HH:mm:ss,一周前2010-09-12 HH:mm:ss

谢谢

【问题讨论】:

标签: java android date


【解决方案1】:

解析日期:

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);

【讨论】:

  • 我认为情况正好相反:roll() 在日期调用时不处理月/年变化,而 add() 处理。
【解决方案2】:

我可以看到两种方式:

  1. 使用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);
    
  2. 使用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");
    

解决方案 1 是“官方”的 java 方式,但使用 GregorianCalendar 可能会出现严重的性能问题,因此 Android 工程师添加了 android.text.format.Time 对象来解决此问题。

【讨论】:

  • roll 方法不会影响任何其他字段,因此即使您尝试从月初开始返回 7 天,您也会始终卡在同一个月内。
  • 你说得对,我修正了这个例子。无论如何,我的观点更多地是关于 android.text.format.Time 的使用,如果您要更新 ListView 项目中的日期,这是首选。使用 GregorianCalendar 可能会阻止您的列表快速滚动。
  • 谢谢各位程序员,注意这里的第一个例子应该格式化 (someDate.getTime()) 而不仅仅是 someDate
  • 时间已被弃用。
【解决方案3】:

我创建了自己的函数,可能有助于从中获取下一个/上一个日期

当前日期:

/**
 * 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

【讨论】:

  • 哇.. 很好的答案。只找这个。
  • 第二个函数应该返回s.format(cal.getTime())
【解决方案4】:

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

现代方法使用 java.time 类。

LocalDate 类表示没有时间和时区的仅日期值。

时区对于确定日期至关重要。对于任何给定的时刻,日期在全球范围内因区域而异。例如,Paris France 中午夜后几分钟是新的一天,而 Montréal Québec 中仍然是“昨天”。

continent/region 的格式指定proper time zone name,例如America/MontrealAfrica/CasablancaPacific/Auckland。切勿使用 3-4 个字母的缩写,例如 ESTIST,因为它们不是真正的时区,没有标准化,甚至不是唯一的 (!)。

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。所以用空格替换T

output = output.replace( "T" , " " ) ;

关于java.time

java.time 框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧 legacy 日期时间类,例如 java.util.DateCalendarSimpleDateFormat

Joda-Time 项目现在位于maintenance mode,建议迁移到java.time 类。

要了解更多信息,请参阅Oracle Tutorial。并在 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();

【讨论】:

    【解决方案5】:
    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:

    添加 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 或 ThreeTenABP for Android (minSdk

    ThreeTenABP:

    implementation 'com.jakewharton.threetenabp:threetenabp:1.2.1'
    

    '

    LocalDate now= LocalDate.now();
    now.minusWeeks(1);
    

    【讨论】:

    【解决方案6】:

    您可以使用此代码获取您想要的确切字符串。

    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)
                }
            }
        }
    
    }
    

    【讨论】:

      【解决方案7】:

      试试这个

      一种从当前或绕过获取日期的单一方法 任何日期

      @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))
      }
      

      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()));
      }
      

      用法

      1. getCalculatedDate("", "yyyy-MM-dd", -2) // 如果你想要从今天开始的日期
      2. getCalculatedDate("2019-11-05", "yyyy-MM-dd", -2) // 如果你想要自己的日期

      【讨论】:

      • 这些糟糕的日期时间类在几年前被 JSR 310 中定义的行业领先的 java.time 类所取代。
      【解决方案8】:

      科特林:

      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)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-05-08
        • 2012-03-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-16
        • 1970-01-01
        相关资源
        最近更新 更多