22

I want to get date from 7 days ago to today in Kotlin. Any suggestions? This is what I have so far

val date = Calendar.getInstance()

val yesterday = Calendar.getInstance()

yesterday.add(Calendar.DATE,-1)

var todayOrYesterday:String?

var todayDate = date.time

while (todayDate > yesterday.time){

    val formatter = SimpleDateFormat("EEEE, d MMMM yyyy")

    val format = formatter.format(todayDate)

    println(format)

    todayOrYesterday = if (DateUtils.isToday(date.timeInMillis)) {
            "Today"
    }else "Yesterday"

    date.add(Calendar.DATE,-7)
}
KeLiuyue
  • 8,149
  • 4
  • 25
  • 42

3 Answers3

53

Use this function, pass the days ago you want:

fun getDaysAgo(daysAgo: Int): Date {
    val calendar = Calendar.getInstance()
    calendar.add(Calendar.DAY_OF_YEAR, -daysAgo)

    return calendar.time
}
Alex Romanov
  • 11,453
  • 6
  • 48
  • 51
13

Simply use,

val date = Calendar.getInstance()   // 19-01-2018
date.add(Calendar.DATE, -7)         // 12-01-2018
Bhavesh Desai
  • 753
  • 4
  • 20
  • 1
    This troublesome old Class is now legacy, supplanted by the *java.time* classes. For older Android see the ThreeTen-Backport and ThreeTenABP projects. – Basil Bourque Jan 19 '18 at 20:48
0

An alternative is to use Joda Time (Joda Time for Android). This library has a really nice API.

DateTime.now().minusDays(7)

And you can call .toDate() if you need a Java-Date object.

Link: Why Joda Time?

Kevin Robatel
  • 8,025
  • 3
  • 44
  • 57
  • 2
    The Joda-Time project is now in maintenance mode, with the team advising migration to the *java.time* classes. For earlier Android see the *ThreeTen-Backport* and *ThreeTenABP* projects. – Basil Bourque Jan 19 '18 at 20:47