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.
This tutorial explains how to get the Current Date and time in Swift with examples.
Date()
functionDateFormatter.setLocalizedDateFormatFromTemplate("MM/dd/yyyy")
DateFormatter.long
propertyDate
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()
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
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
🧮 Tags
Recent posts
Puppeteer Login Test example How to convert Double to Integer or Integer to double in Dart| Flutter By Example Best ways to fix 504 gateway time out in nodejs Applications Fix for Error No configuration provided for scss Multiple ways to List containers in a Docker with examplesRelated posts