获取上周一的日期

时间:2019-01-14 07:49:46

标签: date tcl

我想获取给定日期的最后一个星期一日期。例如,如果我的输入为190113,则我希望输出为190107,即上周一。

if {$current_date == "Mon"} {

    set startday [clock seconds]
    set startday [clock format $startday -format %y%m%d]
    puts $startday

} else {

    puts "no monday today"
    #I don't know how to get last monday date


}

2 个答案:

答案 0 :(得分:8)

这可以通过利用clock scan具有相当复杂的解析器这一事实而非常简单地完成,您可以通过-base选项提供所有内容都相对于其的时间戳。另外,clock scanclock format都具有-format选项,以便您可以准确指定输入和输出数据中发生的事情。

proc getLastMonday {baseDate} {
    set base [clock scan $baseDate -format "%y%m%d"]
    set timestamp [clock scan "12:00 last monday" -base $base]
    return [clock format $timestamp -format "%y%m%d"]
    # This would work as a one-liner, provided you like long lines
}

演示:

puts [getLastMonday 190113];  # ==> 190107
puts [getLastMonday 190131];  # ==> 190128

答案 1 :(得分:0)

参考:https://www.tcl.tk/man/tcl/TclCmd/clock.htm#M22

这是用于此目的的示例代码段。添加了内联注释以供理解:

proc get_last_monday_date {date} {
  # Get the end timestamp for the specified date
  set end_timestamp [clock scan ${date}-23:59:59 -format %y%m%d-%H:%M:%S]

  # Get day of the week for the current date
  set day_of_week [clock format $end_timestamp -format %u]

  # Sunday may report as 0 or 7. If 0, change to 7
  # if {$day_of_week == 0} {
  #     set day_of_week 7
  # }

  # Monday is 1st day of the week. Monday = 1.
  # Find how many days to go back in time
  set delta_days [expr $day_of_week - 1]

  # Multiply the delta by 24 hours and subtract from end of the day timestamp
  # Get the timestamp for the result. That's last Monday's timestamp.
  return [clock format [clock add $end_timestamp -[expr $delta_days * 24] hours] -format %D]

}
puts "Last Monday for 01-Jan-2019:  [get_last_monday_date 190101]"
puts "Last Monday for 06-Jan-2019:  [get_last_monday_date 190106]"
puts "Last Monday for 15-Jan-2019:  [get_last_monday_date 190115]"
puts "Last Monday for 31-Jan-2019:  [get_last_monday_date 190131]"

执行输出:

Last Monday for 01-Jan-2019:  12/31/2018
Last Monday for 06-Jan-2019:  12/31/2018
Last Monday for 15-Jan-2019:  01/14/2019
Last Monday for 31-Jan-2019:  01/28/2019