Created
May 26, 2024 01:44
-
-
Save amosgyamfi/287af9275f52585bd2c08fd9e776e0ef to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// DateAndTimeInterval.swift | |
// SwiftUIDevTips | |
// | |
// TimeInterval is the length of time in seconds | |
// | |
import SwiftUI | |
struct DateAndTimeInterval: View { | |
var aMinute: TimeInterval = 60.0 | |
let anHour = 3600.0 | |
let aDay = 3600.0 * 24.0 | |
var body: some View { | |
NavigationStack { | |
List { | |
// Text("\(aMinute)") | |
// Minute | |
Text("**Minute**: \(String(format: "%.1f", aMinute)) sec") | |
// Hour | |
Text("**Hour**: \(String(format: "%.1f", anHour)) sec") | |
// Day | |
Text("**Day**: \(String(format: "%.1f", aDay)) sec") | |
// Today | |
Text("**Today**: \(Date.now, format: .dateTime)") | |
// An hour from now | |
Text("**An hour from now**: \(Date(timeIntervalSinceNow: anHour).formatted())") | |
// An hour ago | |
Text("**An hour ago**: \(Date(timeIntervalSinceNow: -anHour), format: .dateTime)") | |
// Tomorrow but 2 hours from now | |
Text("**Tomorrow but 2 hours from now**: \(Date(timeInterval: aDay + anHour, since: Date(timeIntervalSinceNow: anHour)), format: .dateTime)") | |
// Add a date formatter, change locale | |
let targetDate = Date(timeInterval: aDay + anHour, since: Date(timeIntervalSinceNow: anHour)) | |
let formattedDate = formattedDateString(for: targetDate) | |
// Tomorrow, 2 hours from now but in Sanfrancisco time zone | |
Text("**Tomorrow, 2 hours from now but in Sanfrancisco time zone**: \(formattedDate)") | |
} | |
.navigationTitle("Date and TimeInterval") | |
.navigationBarTitleDisplayMode(.inline) | |
} | |
} | |
func formattedDateString(for date: Date) -> String { | |
let dateFormatter = DateFormatter() | |
dateFormatter.dateStyle = .medium // .short | |
dateFormatter.timeStyle = .medium // .short | |
/** | |
1. Denmark: da_DK | |
2. Sweden: sv_SE | |
3. Norway: nb_NO | |
4. Finland: fi_FI | |
5. Iceland: is_IS | |
**/ | |
dateFormatter.locale = Locale(identifier: "en_US_POSIX") | |
dateFormatter.timeZone = TimeZone(identifier: "America/Los_Angeles") // TimeZone for San Francisco, California | |
return dateFormatter.string(from: date) | |
} | |
} | |
#Preview { | |
DateAndTimeInterval() | |
.preferredColorScheme(.dark) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment