Yogesh Chauhan's Blog

How to get current timestamp in Swift 4 and 5?

in Swift on April 28, 2020

Solution for Swift 4 and 5


let date = Date()
let format = DateFormatter()
format.dateFormat = "yyyy-MM-dd HH:mm:ss"
let timestamp = format.string(from: date)

now you can use that timestamp anywhere you want. 

Discussion

Date

A specific point in time, independent of any calendar or time zone.

A Date value encapsulate a single point in time, independent of any particular calendrical system or time zone. Date values represent a time interval relative to an absolute reference date.

The Date structure provides methods for comparing dates, calculating the time interval between two dates, and creating a new date from a time interval relative to another date.

We can use date values in conjunction with DateFormatter instances to create localized representations of dates and times and with Calendar instances to perform calendar arithmetic.

Date bridges to the NSDate class. You can use these interchangeably in code that interacts with Objective-C APIs.

DateFormatter

It's a formatter that converts between dates and their textual representations.

Instances of DateFormatter create string representations of NSDate objects, and convert textual representations of dates and times into NSDate objects.

For user-visible representations of dates and times, DateFormatter provides a variety of localized presets and configuration options.

For fixed format representations of dates and times, you can specify a custom format string.

Note:

When working with date representations in ISO 8601 format, use ISO8601DateFormatter instead.

To represent an interval between two NSDate objects, use DateIntervalFormatter instead.

To represent a quantity of time specified by an NSDateComponents object, use DateComponentsFormatter instead.

Sources


Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 How to add Read More Read Less Button using JavaScript? #3 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #4 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #5 How to uninstall Cocoapods from the Mac OS? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
How to use [] (square brackets) function in Envision Basic?Envision BasicSolution to Precision Problem in JavaScript NumbersJavaScriptImplicit and Explicit Joins in Oracle SQLSQL/MySQLAll possible ways you can Insert Data in PostgresPostgresHow does @extend rule work in SCSS (Sass)?SCSSQuery to increment or decrement value in MySQL ignoring negative valuesSQL/MySQL