使用CVCalendar库时Date()获取当前时间偏差1小时的问题求助
Hey there! Let’s break down why you’re seeing that 1-hour time difference and how to fix it for your CVCalendar setup.
First, a quick clarification: Date() in Swift is just a timestamp representing a single moment in time—it doesn’t have a timezone attached. When you print it directly, it defaults to showing UTC, which is why your output is 2019-11-19 14:32:03 +0000 while Norway’s local time (CET/UTC+1 back in November 2019) is an hour ahead.
Here are three concrete steps to resolve this:
Format dates to show local Norwegian time
If you need to display the correct local time in logs or UI, useDateFormatterwith Norway’s timezone. Here’s a code snippet:let dateFormatter = DateFormatter() // Set to Norway's specific timezone dateFormatter.timeZone = TimeZone(identifier: "Europe/Oslo") // Or use the device's current timezone (works if user has it set correctly) // dateFormatter.timeZone = .current dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z" let localDateString = dateFormatter.string(from: Date()) print("Local Date: \(localDateString)") // Will output 2019-11-19 15:32:03 +0100Configure CVCalendar to use the correct timezone
CVCalendar relies onCalendarinstances to handle date logic. Make sure you pass a calendar configured with Norway’s timezone to the component. For example:// Create a custom calendar with Norway's timezone var norwegianCalendar = Calendar.current norwegianCalendar.timeZone = TimeZone(identifier: "Europe/Oslo")! // Assign it to your CVCalendar view let calendarView = CVCalendarView(frame: yourFrame) calendarView.calendar = norwegianCalendar // If using delegates, you might also need to return this calendar in delegate methods func presentedCalendar() -> Calendar { return norwegianCalendar }This ensures CVCalendar calculates and displays dates based on Norway’s local timezone instead of UTC.
Check your device’s system timezone
Sometimes the simplest fix is verifying your device’s timezone settings. On iOS, go to Settings > General > Date & Time and ensure either:- "Set Automatically" is enabled (so it picks up Norway’s timezone based on location), or
- You manually select "Oslo" from the timezone list.
Remember, the underlying Date() value is accurate—you just need to handle timezone conversion for display and ensure your calendar component uses the right context.
内容的提问来源于stack exchange,提问作者Camile

