malcommac / SwiftDate

🐔 Toolkit to parse, validate, manipulate, compare and display dates, time & timezones in Swift.
MIT License
7.61k stars 767 forks source link

Is there a way to format Date with specific timezone? #798

Open kyleduo opened 2 years ago

kyleduo commented 2 years ago

As mentioned in the doc's date formatting section, we can specific a locale to affect the style of formatting. But can we also specific a timezone used when formatting?

// Maybe feasible solution

let date = Date() // 2022-08-16 16:06:26 +0000
let formattedInCurrentTimeZone = date.toFormat("yyyy-MM-dd HH:mm:ssZZZZZ") // current time zone, CST. 2022-08-17 00:06:26+0800
let formattedInEST = date.toFormat("yyyy-MM-dd HH:mm:ssZZZZZ", timezone: .init("EST")) // 2022-08-16 12:06:26-0400

When formatting a Date, timezone is a required arguments since Date is a wrapper of timestamp which is an absolute value, however if we format the Date to a String, we need consider the timezone since a String representing a Date is a relative value. The locale and timezone could be different on a device. So we can not infer timezone from locale.

Thanks.