{

How to get Current Date and Time in Swift with examples


Current Date and time short and long format code swift example

This tutorial explains how to get the Current Date and time in Swift with examples.

  • Current Date and time in Swift using Date() function
  • current Date in Short Format using DateFormatter.setLocalizedDateFormatFromTemplate("MM/dd/yyyy")
  • get Time without Date using DateFormatter.long property

How to get the Current Date and time in Swift?

Date class provides an access to the date and time of UTC timezone.

Here is an example

import Foundation
let date = Date()
print(date)
2022-10-30 11:16:49 +0000

The date object returns the format as per the code running on the device or web.

import Foundation /runpkg/Sources/runpkg/main.swift:1:12: error: cannot find ‘Date’ in scope let date = Date()

How to get the current Date in Short Format in Swift

Swift provides DateFormatter that formats the string with the given format string. DateFormatter.setLocalizedDateFormatFromTemplate accepts MM/dd/yyyy

import Foundation
let date = Date()
print(date)
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale.current
dateFormatter.setLocalizedDateFormatFromTemplate("MM/dd/yyyy")
let shortDate = dateFormatter.string(from: date)
print(shortDate)

Output

07/03/2022

Similarly, you can set DateFormatter.dateStyle to short as given below

import Foundation
let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale.current
dateFormatter.dateStyle = .short
let shortDate = dateFormatter.string(from: date)
print(shortDate)

Output:

7/3/22

How to get Time without Date in swift with example

DateFormatter contains two properties, change it as given below

  • timeStyle to .long
  • dateStyle to .none

Here is an example

import Foundation
let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.timeStyle = .long
dateFormatter.dateStyle = .none
let timeOnly = dateFormatter.string(from: date)
print(timeOnly)

Output:

6:03:27 AM GMT
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.