Short answer

To send a date picked in a UIDatePicker to an API, keep the picked value as a Date and format it only when you build the request, with a DateFormatter set to the en_US_POSIX locale, the Gregorian calendar, the user's time zone and the format yyyy-MM-dd. A formatter left on the device's settings wrote the sample date as 2561-5-2 under a Thai region and 0030-5-2 under the Japanese calendar. Send the body as a Codable struct with URLSession.

SWIFT TIPS · UIKIT · DATES

First posted on May 21, 2018, as "POST Alamofire Date and Gender". Rewritten on November 18, 2026. The date tests were run on a Mac with Swift 6.2.3 (Xcode 26.2) on macOS 26.0.1, and the request against a local test server on 127.0.0.1 with sample values. The screen was type-checked against the iOS 26.2 SDK in Swift 5 and Swift 6 modes with iOS 15 and iOS 26.2 as deployment targets, but not run on a device.

In 2018 I had a profile screen with two buttons, Pria (male) and Wanita (female), and a text field for the date of birth that opened a date picker. Tapping a button set a value to 0 or 1 and colored the buttons. The Done button formatted the picked date twice, once as "22 March 2018" for the field and once as "2018-5-22" for the API, and saved the second string in UserDefaults. The submit button read it back and posted both values with Alamofire as JSON.

The post listed what the format letters mean: d for day, M for month, y for year, h, m and s for hours, minutes and seconds. Those letters are where the trouble is, because a formatter also uses settings you didn't write.

What the 2018 formatter wrote under other region settings

A DateFormatter uses the device's locale and calendar unless you set them. I formatted one moment, May 2, 2018 at 00:30 in Jakarta, with the 2018 format under five region settings, then with a formatter set to UTC, then with the fix:

2018 format "yyyy-M-d" with the device's region:
  id_ID                    -> 2018-5-2
  en_US                    -> 2018-5-2
  th_TH                    -> 2561-5-2
  ja_JP@calendar=japanese  -> 0030-5-2
  ar_SA                    -> 1439-8-16   (printed in Arabic-Indic digits)
Same moment formatted in UTC: 2018-05-01
Fixed formatter, Jakarta time zone: 2018-05-02
ISO8601DateFormatter .withFullDate:  2018-05-02
Text shown in the field (id_ID, .long): 2 Mei 2018
  • The year follows the device's calendar. With Thailand's region the Buddhist calendar is used, so 2018 came out as 2561. With the Japanese calendar it was year 30 of the Heisei era, written 0030. With Saudi Arabia's region it was the Islamic year 1439, in Arabic-Indic digits. The server gets a date it can't read, or reads wrongly, and only for those users.
  • Single letters aren't padded. "yyyy-M-d" gives 2018-5-2. An API that expects an ISO 8601 date wants 2018-05-02, which is what "MM" and "dd" give.
  • UTC can move the day. Apple's DateFormatter documentation says that for most fixed formats you should set the POSIX locale and UTC. That's right for timestamps. A birth date is different: it's a calendar day the person picked in their own time zone. Formatted in UTC, the Jakarta date before 07:00 became May 1. Format it in the time zone the picker used.

The date also lived in UserDefaults

Done saved the API string under the key "date", and the submit button read that key back. I ran the same flow against a separate test store:

2018 flow, first visit, date not picked: tanggal_lahir = ""
2018 flow, user A picks 1990-1-15:       tanggal_lahir = "1990-1-15"
2018 flow, later visit, date not picked:  tanggal_lahir = "1990-1-15" (left over from before)
New body as the server received it: {"contentType": "application/json", "raw": "{\"gender\":1,\"tanggal_lahir\":\"2018-05-02\"}", "json": {"gender": 1, "tanggal_lahir": "2018-05-02"}}
ProfileService.update to /echo-json: OK
ProfileService.update to /nope: Not found
  • On a first visit without picking a date, the request sent an empty string as the birth date.
  • After one person picked a date, every later visit sent that date even when nobody picked one, because UserDefaults keeps values across launches and across accounts on the same phone. A value that only matters while the screen is open belongs in a property of the screen.

The last three lines are the new code below: the body as the test server received it, a normal save, and the server's own "Not found" message coming back as the error for a wrong path.

The model and the request

import Foundation

/// The two values the 2018 API used for gender.
enum Gender: Int, Encodable, Sendable {
    case male = 0
    case female = 1
}

/// Formats a calendar date the way an API expects it: "2018-05-02", whatever the
/// device's language, region or calendar is.
enum APIDate {
    static func string(from date: Date, timeZone: TimeZone = .current) -> String {
        let formatter = DateFormatter()
        formatter.locale = Locale(identifier: "en_US_POSIX")
        formatter.calendar = Calendar(identifier: .gregorian)
        formatter.timeZone = timeZone    // the zone the user picked the date in
        formatter.dateFormat = "yyyy-MM-dd"
        return formatter.string(from: date)
    }
}

/// The JSON body. CodingKeys keep the API's field names out of the Swift names.
struct ProfileUpdate: Encodable, Sendable {
    let gender: Gender
    let birthDate: String

    enum CodingKeys: String, CodingKey {
        case gender
        case birthDate = "tanggal_lahir"
    }
}

enum ProfileError: LocalizedError {
    case server(status: Int, message: String?)

    var errorDescription: String? {
        switch self {
        case .server(_, let message?): return message
        case .server(let status, nil): return "The server answered with status \(status). Please try again."
        }
    }
}

struct ProfileService: Sendable {
    let url: URL
    let token: String
    var session: URLSession = .shared

    func update(_ profile: ProfileUpdate) async throws {
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
        request.httpBody = try JSONEncoder().encode(profile)

        let (data, response) = try await session.data(for: request)
        let status = (response as? HTTPURLResponse)?.statusCode ?? 0
        guard (200..<300).contains(status) else {
            struct Message: Decodable { let message: String }
            throw ProfileError.server(status: status, message: try? JSONDecoder().decode(Message.self, from: data).message)
        }
    }
}

The screen

import UIKit

final class BirthDateGenderViewController: UIViewController {
    private let genderControl = UISegmentedControl(items: ["Male", "Female"])
    private let dateField = UITextField()
    private let datePicker = UIDatePicker()
    private let saveButton = UIButton(configuration: .filled())
    private let service: ProfileService

    private var birthDate: Date?          // the picked date, kept as a Date, not as text

    init(service: ProfileService) {
        self.service = service
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .systemBackground
        title = "Your Profile"

        genderControl.selectedSegmentIndex = UISegmentedControl.noSegment   // nothing chosen yet

        datePicker.datePickerMode = .date
        datePicker.preferredDatePickerStyle = .wheels    // the wheel style fits a keyboard-sized input view
        datePicker.maximumDate = Date()                  // no birth dates in the future
        datePicker.addAction(UIAction { [weak self] _ in self?.pickerChanged() }, for: .valueChanged)

        let toolbar = UIToolbar()
        toolbar.sizeToFit()
        toolbar.items = [
            UIBarButtonItem(systemItem: .flexibleSpace),
            UIBarButtonItem(systemItem: .done, primaryAction: UIAction { [weak self] _ in
                self?.pickerChanged()
                self?.view.endEditing(true)
            }),
        ]
        dateField.placeholder = "Date of birth"
        dateField.borderStyle = .roundedRect
        dateField.inputView = datePicker
        dateField.inputAccessoryView = toolbar
        dateField.tintColor = .clear                     // hide the text cursor

        saveButton.configuration?.title = "Save"
        saveButton.addAction(UIAction { [weak self] _ in self?.save() }, for: .touchUpInside)

        let stack = UIStackView(arrangedSubviews: [genderControl, dateField, saveButton])
        stack.axis = .vertical
        stack.spacing = 16
        stack.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(stack)
        NSLayoutConstraint.activate([
            stack.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 24),
            stack.leadingAnchor.constraint(equalTo: view.layoutMarginsGuide.leadingAnchor),
            stack.trailingAnchor.constraint(equalTo: view.layoutMarginsGuide.trailingAnchor),
        ])
    }

    private func pickerChanged() {
        birthDate = datePicker.date
        // Shown to the person: localized, for example "2 Mei 2018" or "May 2, 2018".
        dateField.text = DateFormatter.localizedString(from: datePicker.date, dateStyle: .long, timeStyle: .none)
    }

    private func save() {
        guard let gender = Gender(rawValue: genderControl.selectedSegmentIndex), let birthDate else {
            showMessage("Please choose your gender and date of birth first.")
            return
        }
        let update = ProfileUpdate(gender: gender, birthDate: APIDate.string(from: birthDate, timeZone: datePicker.timeZone ?? .current))
        saveButton.isEnabled = false
        saveButton.configuration?.showsActivityIndicator = true
        Task { [weak self, service] in
            defer {
                self?.saveButton.isEnabled = true
                self?.saveButton.configuration?.showsActivityIndicator = false
            }
            do {
                try await service.update(update)
                self?.navigationController?.popViewController(animated: true)
            } catch {
                self?.showMessage(error.localizedDescription)
            }
        }
    }

    private func showMessage(_ message: String) {
        let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .default))
        present(alert, animated: true)
    }
}

How it works

  • One value, two texts. birthDate stays a Date. The field shows DateFormatter.localizedString with the long style, "2 Mei 2018" or "May 2, 2018" depending on the person's language. The API gets APIDate.string, which is 2018-05-02 on every device.
  • Gender as an enum. Gender has the raw values 0 and 1 that the 2018 API used, and encodes as a number. A segmented control with no segment selected replaces the value 2 the 2018 code used for "nothing chosen yet": Gender(rawValue: -1) is nil, so the guard catches it and shows a message.
  • CodingKeys. The JSON field stays tanggal_lahir while the Swift property reads birthDate.
  • The picker. preferredDatePickerStyle exists since iOS 13.4. Apple's documentation says the default is .automatic and that with .wheels editing happens inline, in the wheels, which is what you want when the picker takes the keyboard's place. maximumDate = Date() stops future birth dates.
  • The button shows the wait. The spinner and isEnabled = false stop a second tap from sending the request twice, and defer turns both back whichever way the request ends.
  • The token. The service sends Bearer and a token it's given. Keep the token in the Keychain; the sign-in post linked below shows how.

A quick check for your project

  1. Search for dateFormat = in code that builds request bodies or URLs. Each formatter there needs locale = Locale(identifier: "en_US_POSIX") and a Gregorian calendar.
  2. On a test device, set the region to Thailand or the calendar to Japanese, then send a date and look at what the server received.
  3. Search for UserDefaults keys written in one method and read in another method of the same screen.

What the 2018 version said

The original sent the request to a placeholder address, https://yourAPi, with the header "Authorization": "Token", and printed the response. Its screenshot shows something else worth knowing: the field reads "22 March 2018" while the picker's months are in Indonesian, because the picker's locale was set to "id" and the field's formatter wasn't. It also built a toolbar in viewDidLoad that was never attached to anything.

The 2018 screen: a date field showing 22 March 2018, Pria and Wanita buttons, and a date picker with Indonesian month names

Sources