简体   繁体   English

Android 在 7 天(一周)之前获取日期

[英]Android get date before 7 days (one week)

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谢谢

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

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

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 France is a new day while still “yesterday” in Montréal Québec .例如,在法国巴黎午夜过后几分钟是新的一天,而在魁北克蒙特利尔仍然是“昨天”。

Specify a proper time zone name in the format of continent/region , such as America/Montreal , Africa/Casablanca , or Pacific/Auckland .continent/region的格式指定正确的时区名称,例如America/MontrealAfrica/CasablancaPacific/Auckland Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).永远不要使用ESTIST等 3-4 个字母的缩写,因为它们不是真正的时区,不是标准化的,甚至不是唯一的(!)。

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.让 java.time 确定您所需时区的一天中的第一个时刻。 Do not assume the day starts at 00:00:00 .不要假设一天从00:00:00开始。 Anomalies such as Daylight Saving Time means the day may start at another time-of-day such as 01:00:00 .夏令时等异常意味着一天可能从另一个时间开始,例如01:00:00

ZonedDateTime weekAgoStart = weekAgo.atStartOfDay( z ) ;

Generate a string representing this ZonedDateTime object using a DateTimeFormatter object.使用DateTimeFormatter对象生成表示此ZonedDateTime对象的字符串。 Search Stack Overflow for many more discussions on this class.搜索 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.该标准格式接近您想要的格式,但在您想要空格的中间有一个T So substitute SPACE for T .所以用 SPACE 代替T

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

About java.time关于 java.time

The java.time framework is built into Java 8 and later. java.time框架内置于 Java 8 及更高版本中。 These classes supplant the troublesome old legacy date-time classes such as java.util.Date , Calendar , & SimpleDateFormat .这些类取代麻烦的老传统日期时间类,如java.util.DateCalendar ,和SimpleDateFormat

The Joda-Time project, now in maintenance mode , advises migration to the java.time classes.现在处于维护模式Joda-Time项目建议迁移到java.time类。

To learn more, see the Oracle Tutorial .要了解更多信息,请参阅Oracle 教程 And search Stack Overflow for many examples and explanations.并在 Stack Overflow 上搜索许多示例和解释。 Specification is JSR 310 .规范是JSR 310

Where to obtain the java.time classes?从哪里获得 java.time 类?

Joda-Time乔达时间

Update: The Joda-Time project is now in maintenance mode.更新: Joda-Time 项目现在处于维护模式。 The team advises migration to the java.time classes.该团队建议迁移到 java.time 类。

Using the Joda-Time library 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();

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用法

  1. getCalculatedDate("", "yyyy-MM-dd", -2) // If you want date from today getCalculatedDate("", "yyyy-MM-dd", -2) // 如果你想要今天的日期
  2. getCalculatedDate("2019-11-05", "yyyy-MM-dd", -2) // If you want date from your own getCalculatedDate("2019-11-05", "yyyy-MM-dd", -2) // 如果你想要你自己的日期

I can see two ways:我可以看到两种方式:

  1. Use aGregorianCalendar :使用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. Use a android.text.format.Time :使用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");

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 对象来解决此问题。

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

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

}

Kotlin:科特林:

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)

Usage:用法:

val newDate = oldDate - 1.week
// Or val newDate = oldDate.minus(1.week)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM