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

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

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

问题

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

开始日期将是星期一。

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

private var thisWeekStart: Long = 0
private var thisWeekEnd: Long = 0
private var lastWeekStart: Long = 0
private var lastWeekEnd: Long = 0

我尝试像下面这样赋值:

var cal = Calendar.getInstance()
cal.time = Date()
thisWeekEnd = cal.timeInMillis

// 本周开始
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY)
thisWeekStart = cal.timeInMillis

cal.add(Calendar.DAY_OF_WEEK, -7)
lastWeekStart = cal.timeInMillis

cal.add(Calendar.DAY_OF_WEEK, 6)
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.

private var thisWeekStart : Long = 0
    private var thisWeekEnd : Long = 0
    private var lastWeekStart : Long = 0
    private var lastWeekEnd : Long = 0

And I tried to assign something like below..

var cal = Calendar.getInstance()
        cal.time = Date()
        thisWeekEnd = cal.timeInMillis

        // 이번주 시작
        cal.get(Calendar.DAY_OF_WEEK)
        thisWeekStart = cal.timeInMillis

        cal.add(Calendar.DAY_OF_WEEK, -1)
        lastWeekStart = cal.timeInMillis

        cal.clear()
        cal.set(Calendar.DAY_OF_WEEK, -1)
        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

// tl;dr

使用 *java.time*

(使用Java语法而不是Kotlin)

英文:

tl;dr

Use java.time.

(In Java syntax rather than Kotlin.)

LocalDate                                    // Represent a date-only value.
.now( ZoneId.of( "Asia/Seoul" ) )            // Get the current date as seen in a particular time zone.
.with( 
    TemporalAdjusters.previousOrSame( DayOfWeek.MONDAY ) 
)                                            // Returns another LocalDate. 
.atStartOfDay( ZoneId.of( "Asia/Seoul" ) )   // Determine the first moment of the day on that date in that time zone.
.toInstant()                                 // Convert to UTC. Same moment, same point on the timeline.
.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):

LocalDate today = LocalDate.now() ;

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

ZoneId zoneId = ZoneId.of( "Asia/Seoul" ) ; // Or ZoneId.systemDefault(). 
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.

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

To get the following Sunday, add 6 days.

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.

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.

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.

Instant instant = zdtStart.toInstant() ;

From the Instant extract a count from epoch.

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

Compare

See if a moment lies within that week.

long now = Instant.now().toMilli() ;
if ( 
   ( ! now < start )
    &&
   ( now < end )
) { … }

答案2

得分: 0

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

希望这对您有帮助!

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

Hope this would help!

答案3

得分: 0

以下是翻译好的部分:

首先,我们定义我们期望的输出格式。在这种情况下,我们将使用`yyyy-MM-dd`格式。在下一步中,我们将当前日期保存在一个变量中。在第三行,我们定义了我们正在使用的时区(我在测试中使用了`Europe/Berlin`,因为我在德国)。

在接下来的步骤中,我们为每个期望的日期创建了`Calendar`实例,并根据我们的需求操作日期。

重要提示:只有在您的一周开始日期不是星期日时,您才需要添加`firstDayOfWeek = Calendar.MONDAY`这一行。

    val dateFormat = SimpleDateFormat("yyyy-MM-dd")
    val today = Calendar.getInstance()
    val timeZone = TimeZone.getTimeZone("Europe/Berlin")

    val startOfWeek = Calendar.getInstance(timeZone).apply {
        firstDayOfWeek = Calendar.MONDAY
        set(Calendar.DAY_OF_WEEK, Calendar.MONDAY)
    }.time

    val endOfWeek = Calendar.getInstance(timeZone).apply {
        firstDayOfWeek = Calendar.MONDAY
        set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY)
    }.time

    val startOfLastWeek = Calendar.getInstance(timeZone).apply {
        firstDayOfWeek = Calendar.MONDAY
        set(Calendar.WEEK_OF_YEAR, today.get(Calendar.WEEK_OF_YEAR) - 1)
        set(Calendar.DAY_OF_WEEK, Calendar.MONDAY)
    }.time

    val endOfLastWeek = Calendar.getInstance(timeZone).apply {
        firstDayOfWeek = Calendar.MONDAY
        set(Calendar.WEEK_OF_YEAR, today.get(Calendar.WEEK_OF_YEAR) - 1)
        set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY)
    }.time

    val startOfWeekAsString = dateFormat.format(startOfWeek)
    val endOfWeekAsString = dateFormat.format(endOfWeek)
    val startOfLastWeekAsString = dateFormat.format(startOfLastWeek)
    val endOfLastWeekAsString = dateFormat.format(endOfLastWeek)

    println("Start of week: $startOfWeekAsString")
    println("End of week: $endOfWeekAsString")
    println("Start of last week: $startOfLastWeekAsString")
    println("End of last week: $endOfLastWeekAsString")

期望的输出:

Start of week: 2023-02-13
End of week: 2023-02-19
Start of last week: 2023-02-06
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.

val dateFormat = SimpleDateFormat(&quot;yyyy-MM-dd&quot;)
val today = Calendar.getInstance()
val timeZone = TimeZone.getTimeZone(&quot;Europe/Berlin&quot;)

val startOfWeek = Calendar.getInstance(timeZone).apply {
    firstDayOfWeek = Calendar.MONDAY
    set(Calendar.DAY_OF_WEEK, Calendar.MONDAY)
}.time

val endOfWeek = Calendar.getInstance(timeZone).apply {
    firstDayOfWeek = Calendar.MONDAY
    set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY)
}.time

val startOfLastWeek = Calendar.getInstance(timeZone).apply {
    firstDayOfWeek = Calendar.MONDAY
    set(Calendar.WEEK_OF_YEAR, today.get(Calendar.WEEK_OF_YEAR) - 1)
    set(Calendar.DAY_OF_WEEK, Calendar.MONDAY)
}.time

val endOfLastWeek = Calendar.getInstance(timeZone).apply {
    firstDayOfWeek = Calendar.MONDAY
    set(Calendar.WEEK_OF_YEAR, today.get(Calendar.WEEK_OF_YEAR) - 1)
    set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY)
}.time

val startOfWeekAsString = dateFormat.format(startOfWeek)
val endOfWeekAsString = dateFormat.format(endOfWeek)
val startOfLastWeekAsString = dateFormat.format(startOfLastWeek)
val endOfLastWeekAsString = dateFormat.format(endOfLastWeek)

println(&quot;Start of week: $startOfWeekAsString&quot;)
println(&quot;End of week: $endOfWeekAsString&quot;)
println(&quot;Start of last week: $startOfLastWeekAsString&quot;)
println(&quot;End of last week: $endOfLastWeekAsString&quot;)

Expected output:

Start of week: 2023-02-13
End of week: 2023-02-19
Start of last week: 2023-02-06
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:

确定