簡體   English   中英

在Swift中的特定時間創建本地日期

[英]Create a local date at a specific time in Swift

我在Swift中為我的應用程序處理本地時間日期時遇到問題。 我想在午夜創建今天的日期,在23:59創建另一個實例。 基本上,有2個日期可以覆蓋當天的整個日期(想法是加載今天的所有日歷條目)。 我在操場上的代碼:

import Foundation

let dateFormatter = DateFormatter()
let date = Date()
dateFormatter.dateFormat = "yyyy-MM-dd"


let todayStartDate = dateFormatter.date(from: dateFormatter.string(from: date))
let todayEndDate = dateFormatter.date(from: dateFormatter.string(from: Calendar.current.date(byAdding: .day, value: 1, to: date)!))


print(todayStartDate!)
print(todayEndDate!)

我最終有時間在那里:

“ 2018年1月27日,12:00 AM”

打印輸出:

“ 2018-01-26 23:00:00 +0000 \\ n”

答案(如評論中所述)是: print顯示GMT中的Date實例。 2018-01-26 23:00:00 +0000是與2018-01-26 23:00:00 +0000 2018-01-27 00:00:00 +0100相同的時間點

除此之外,我想提出一種使用Calendar強大的日期數學技能來獲取todayStartDatetodayEndDate更可靠的方法。

let calendar = Calendar.current
var todayStartDate = Date()
var interval = TimeInterval()
calendar.dateInterval(of: .day, start: &todayStartDate, interval: &interval, for: Date())
let todayEndDate = calendar.date(byAdding: .second, value: Int(interval-1), to: todayStartDate)!

print(todayStartDate)
print(todayEndDate)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM