To convert a date string from 'Nov 16, 2022, 12:00:00 AM' to '01/18/2022' in Swift, you can use the following code:

let dateString = 'Nov 16, 2022, 12:00:00 AM'

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = 'MMM dd, yyyy, hh:mm:ss a'

if let date = dateFormatter.date(from: dateString) {
    dateFormatter.dateFormat = 'MM/dd/yyyy'
    let convertedDateString = dateFormatter.string(from: date)
    print(convertedDateString) // Outputs 01/18/2022
}

First, we create a DateFormatter object and set the input date format to 'MMM dd, yyyy, hh:mm:ss a'. Then, we use the dateFormatter.date(from:) method to convert the string to a Date object.

If the conversion is successful, we create another DateFormatter object and set the output date format to 'MM/dd/yyyy'. Finally, we use the dateFormatter.string(from:) method to convert the Date object to a string in the specified format.

Note: In the above example, it is assumed that the input date is in the current device's time zone. If you need to consider other time zones, you can set the dateFormatter.timeZone property to specify a specific time zone.

Swift: Convert Date String from 'Nov 16, 2022, 12:00:00 AM' to '01/18/2022'

原文地址: https://www.cveoy.top/t/topic/pe0y 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录