如何在Kotlin中获取本周的开始和结束日期以及上周的开始和结束日期。

huangapple go评论118阅读模式
英文:

How to get Thisweek start and end date and Lastweek start and end date in Kotlin

问题

我需要获取本周的开始日期,如2023-02-20,以及上周的开始日期和结束日期。

开始日期将是星期一。

所以我创建了4个变量,如下所示:

  1. private var thisWeekStart: Long = 0
  2. private var thisWeekEnd: Long = 0
  3. private var lastWeekStart: Long = 0
  4. private var lastWeekEnd: Long = 0

我尝试像下面这样赋值:

  1. var cal = Calendar.getInstance()
  2. cal.time = Date()
  3. thisWeekEnd = cal.timeInMillis
  4. // 本周开始
  5. cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY)
  6. thisWeekStart = cal.timeInMillis
  7. cal.add(Calendar.DAY_OF_WEEK, -7)
  8. lastWeekStart = cal.timeInMillis
  9. cal.add(Calendar.DAY_OF_WEEK, 6)
  10. lastWeekEnd = cal.timeInMillis

但它返回的是毫秒,而不是yyyy-MM-dd格式。而且我不确定清除日历的方法是否正确。最重要的是,我无法通过上述方法获取上周的结束日期。

有没有更好的方法来获取本周和上周的开始和结束日期?

英文:

I need to get this week startdate like 2023-02-20 and last week startdate and end date.

startdate will be monday.

so I create 4 variables like below.

  1. private var thisWeekStart : Long = 0
  2. private var thisWeekEnd : Long = 0
  3. private var lastWeekStart : Long = 0
  4. private var lastWeekEnd : Long = 0

And I tried to assign something like below..

  1. var cal = Calendar.getInstance()
  2. cal.time = Date()
  3. thisWeekEnd = cal.timeInMillis
  4. // 이번주 시작
  5. cal.get(Calendar.DAY_OF_WEEK)
  6. thisWeekStart = cal.timeInMillis
  7. cal.add(Calendar.DAY_OF_WEEK, -1)
  8. lastWeekStart = cal.timeInMillis
  9. cal.clear()
  10. cal.set(Calendar.DAY_OF_WEEK, -1)
  11. lastWeekStart = cal.timeInMillis

But it throws milliseconds not like yyyy-MM-dd format.

And I'm not sure is that correct way of keep clearing calendar like above.

Most of all, I can't get last week's end date with above way.

Is there any good way to get this weed and last week start, end date?

答案1

得分: 1

  1. // tl;dr
  2. 使用 *java.time*
  3. (使用Java语法而不是Kotlin)
英文:

tl;dr

Use java.time.

(In Java syntax rather than Kotlin.)

  1. LocalDate // Represent a date-only value.
  2. .now( ZoneId.of( "Asia/Seoul" ) ) // Get the current date as seen in a particular time zone.
  3. .with(
  4. TemporalAdjusters.previousOrSame( DayOfWeek.MONDAY )
  5. ) // Returns another LocalDate.
  6. .atStartOfDay( ZoneId.of( "Asia/Seoul" ) ) // Determine the first moment of the day on that date in that time zone.
  7. .toInstant() // Convert to UTC. Same moment, same point on the timeline.
  8. .toEpochMilli() // Extract a count of milliseconds since 1970-01-01T00:00Z.

Avoid legacy classes

The legacy date-time classes are terrible, deeply flawed in their design. They were supplanted years ago by the modern java.time classes built into Java 8 and later.

An implementation is built into Android 26+. For earlier Android, the latest tooling makes most of the java.time functionality available via API desugaring.

java.time

LocalDate

> need to get this week startdate like 2023-02-20

Use the LocalDate class to represent a date only without a time-of-day and without an offset or time zone.

Using Java syntax (I've not yet learned Kotlin):

  1. LocalDate today = LocalDate.now() ;

Generally best to be explicit about the time zone used to determine the current date.

  1. ZoneId zoneId = ZoneId.of( "Asia/Seoul" ) ; // Or ZoneId.systemDefault().
  2. LocalDate today = LocalDate.now() ;

TemporalAdjuster

Use a TemporalAdjuster to move to another day of week. Note the DayOfWeek enum, defining an object for each day of week.

  1. LocalDate previousOrSameMonday = today.with( TemporalAdjusters.previousOrSame( DayOfWeek.MONDAY ) ) ;

To get the following Sunday, add 6 days.

  1. LocalDate sameOrNextSunday = previousOrSameMonday.plusDays( 6 ) ;

But… A span of time is usually better defined using the Half-Open approach. In Half-Open, the beginning is inclusive while the ending is exclusive. So a week starts on a Monday, running up to, but not including, the following Monday.

  1. LocalDate startNextWeek = previousOrSameMonday.plusWeeks( 1 ) ;

Count from epoch

Apparently you want a count of milliseconds from an epoch reference date. I will assume your epoch reference is the first moment of 1970 as seen in UTC, 1970-01-01T00:00Z.

ZonedDateTime

To do this, we need to get the first moment of the day on that date as seen in a particular time zone.

Do not assume the day starts at 00:00. Some days on some dates in some zones start at another time-of-day such as 01:00. Let java.time determine the first moment of the day.

  1. ZonedDateTime zdtStart = previousOrSameMonday.atStartOfDay( zoneId ) ;

Instant

Extract an Instant, the same moment but as seen with an offset from UTC of zero hours-minutes-seconds.

  1. Instant instant = zdtStart.toInstant() ;

From the Instant extract a count from epoch.

  1. long start = instant.toEpochMilli() ;
  2. long end = startNextWeek.atStartOfDay( zoneId ).toInstant().toEpochMilli() ;

Compare

See if a moment lies within that week.

  1. long now = Instant.now().toMilli() ;
  2. if (
  3. ( ! now < start )
  4. &&
  5. ( now < end )
  6. ) { }

答案2

得分: 0

  1. fun getStartAndEndDayByToday(today: Calendar): ArrayList<String> {
  2. val startAndEndDayArray = ArrayList<String>()
  3. // 获取今天是本周的星期几
  4. val todayWeekDay = today.get(Calendar.DAY_OF_WEEK)
  5. // 下面可以获取本周的开始日期;根据本地时区的不同,它会变化
  6. today.add(Calendar.DAY_OF_MONTH, 1 - todayWeekDay)
  7. val calStartDayOfWeek = today.time
  8. // 下面可以获取本周的结束日期;根据本地时区的不同,它会变化
  9. today.add(Calendar.DAY_OF_MONTH, 6)
  10. val calEndDayOfWeek = today.time
  11. // 在这里,您可以使用SimpleDateFormat设置日期格式
  12. val sdfStartDayOfWeek = SimpleDateFormat("yyyy-MM-dd")
  13. val sdfEndDayOfWeek = SimpleDateFormat("yyyy-MM-dd")
  14. // 将开始日期和结束日期添加到数组中
  15. startAndEndDayArray.add(sdfStartDayOfWeek.format(calStartDayOfWeek))
  16. startAndEndDayArray.add(sdfEndDayOfWeek.format(calEndDayOfWeek))
  17. return startAndEndDayArray
  18. }

希望这对您有帮助!

英文:
  1. fun getStartAndEndDayByToday(today: Calendar): ArrayList&lt;String&gt; {
  2. val startAndEndDayArray = ArrayList&lt;String&gt;()
  3. // Get the day of this week today
  4. val todayWeekDay = today.get(Calendar.DAY_OF_WEEK)
  5. // Below you can get the start day of week; it would be changeable according to local time zone
  6. today.add(Calendar.DAY_OF_MONTH, 1 - todayWeekDay)
  7. val calStartDayOfWeek = today.time
  8. // Below you can get the end day of week; it would be changeable according to local time zone
  9. today.add(Calendar.DAY_OF_MONTH, 6)
  10. val calEndDayOfWeek = today.time
  11. // Here you can set the date format by using SimpleDateFormat
  12. val sdfStartDayOfWeek = SimpleDateFormat(&quot;yyyy-MM-dd&quot;)
  13. val sdfEndDayOfWeek = SimpleDateFormat(&quot;yyyy-MM-dd&quot;)
  14. // Make the array with start date and end date
  15. startAndEndDayArray.add(sdfStartDayOfWeek.format(calStartDayOfWeek))
  16. startAndEndDayArray.add(sdfEndDayOfWeek.format(calEndDayOfWeek))
  17. return startAndEndDayArray
  18. }

Hope this would help!

答案3

得分: 0

以下是翻译好的部分:

  1. 首先,我们定义我们期望的输出格式。在这种情况下,我们将使用`yyyy-MM-dd`格式。在下一步中,我们将当前日期保存在一个变量中。在第三行,我们定义了我们正在使用的时区(我在测试中使用了`Europe/Berlin`,因为我在德国)。
  2. 在接下来的步骤中,我们为每个期望的日期创建了`Calendar`实例,并根据我们的需求操作日期。
  3. 重要提示:只有在您的一周开始日期不是星期日时,您才需要添加`firstDayOfWeek = Calendar.MONDAY`这一行。
  4. val dateFormat = SimpleDateFormat("yyyy-MM-dd")
  5. val today = Calendar.getInstance()
  6. val timeZone = TimeZone.getTimeZone("Europe/Berlin")
  7. val startOfWeek = Calendar.getInstance(timeZone).apply {
  8. firstDayOfWeek = Calendar.MONDAY
  9. set(Calendar.DAY_OF_WEEK, Calendar.MONDAY)
  10. }.time
  11. val endOfWeek = Calendar.getInstance(timeZone).apply {
  12. firstDayOfWeek = Calendar.MONDAY
  13. set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY)
  14. }.time
  15. val startOfLastWeek = Calendar.getInstance(timeZone).apply {
  16. firstDayOfWeek = Calendar.MONDAY
  17. set(Calendar.WEEK_OF_YEAR, today.get(Calendar.WEEK_OF_YEAR) - 1)
  18. set(Calendar.DAY_OF_WEEK, Calendar.MONDAY)
  19. }.time
  20. val endOfLastWeek = Calendar.getInstance(timeZone).apply {
  21. firstDayOfWeek = Calendar.MONDAY
  22. set(Calendar.WEEK_OF_YEAR, today.get(Calendar.WEEK_OF_YEAR) - 1)
  23. set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY)
  24. }.time
  25. val startOfWeekAsString = dateFormat.format(startOfWeek)
  26. val endOfWeekAsString = dateFormat.format(endOfWeek)
  27. val startOfLastWeekAsString = dateFormat.format(startOfLastWeek)
  28. val endOfLastWeekAsString = dateFormat.format(endOfLastWeek)
  29. println("Start of week: $startOfWeekAsString")
  30. println("End of week: $endOfWeekAsString")
  31. println("Start of last week: $startOfLastWeekAsString")
  32. println("End of last week: $endOfLastWeekAsString")

期望的输出:

  1. Start of week: 2023-02-13
  2. End of week: 2023-02-19
  3. Start of last week: 2023-02-06
  4. End of last week: 2023-02-12
英文:

At first, we define our desired output format. In this case we will use yyyy-MM-dd. In the next step we save the current date in a variable. In the third line we define timezone in which we are working (I used Europe/Berlin for testing purposes, bacause I'm in germany).

In the next steps we create Calendar instance for each desired date and manipulate the date to our needs.

Important: You have to add the line firstDayOfWeek = Calendar.MONDAY only if your week starts at another date than Sunday.

  1. val dateFormat = SimpleDateFormat(&quot;yyyy-MM-dd&quot;)
  2. val today = Calendar.getInstance()
  3. val timeZone = TimeZone.getTimeZone(&quot;Europe/Berlin&quot;)
  4. val startOfWeek = Calendar.getInstance(timeZone).apply {
  5. firstDayOfWeek = Calendar.MONDAY
  6. set(Calendar.DAY_OF_WEEK, Calendar.MONDAY)
  7. }.time
  8. val endOfWeek = Calendar.getInstance(timeZone).apply {
  9. firstDayOfWeek = Calendar.MONDAY
  10. set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY)
  11. }.time
  12. val startOfLastWeek = Calendar.getInstance(timeZone).apply {
  13. firstDayOfWeek = Calendar.MONDAY
  14. set(Calendar.WEEK_OF_YEAR, today.get(Calendar.WEEK_OF_YEAR) - 1)
  15. set(Calendar.DAY_OF_WEEK, Calendar.MONDAY)
  16. }.time
  17. val endOfLastWeek = Calendar.getInstance(timeZone).apply {
  18. firstDayOfWeek = Calendar.MONDAY
  19. set(Calendar.WEEK_OF_YEAR, today.get(Calendar.WEEK_OF_YEAR) - 1)
  20. set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY)
  21. }.time
  22. val startOfWeekAsString = dateFormat.format(startOfWeek)
  23. val endOfWeekAsString = dateFormat.format(endOfWeek)
  24. val startOfLastWeekAsString = dateFormat.format(startOfLastWeek)
  25. val endOfLastWeekAsString = dateFormat.format(endOfLastWeek)
  26. println(&quot;Start of week: $startOfWeekAsString&quot;)
  27. println(&quot;End of week: $endOfWeekAsString&quot;)
  28. println(&quot;Start of last week: $startOfLastWeekAsString&quot;)
  29. println(&quot;End of last week: $endOfLastWeekAsString&quot;)

Expected output:

  1. Start of week: 2023-02-13
  2. End of week: 2023-02-19
  3. Start of last week: 2023-02-06
  4. End of last week: 2023-02-12

huangapple
  • 本文由 发表于 2023年2月19日 23:50:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/75501348.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定