[ios] iOS Swift - Get the Current Local Time and Date Timestamp

I'm trying to make an attendance app and I am really confused about date and time in iOS and Firebase.

I use date as Key, this is the structure of my Firebase database.

--Employees
  --Unique_ID
     --Details
          Name: John
     --Attendance
          --dateToday
              Timein: 8:00 AM
              Timeout: 5:00 PM
              BreakStart: 12:00 PM
              BreakFinish: 1:00 PM

This is my code to get the date timestamp I used as Key

 override func viewDidLoad() {
     super.viewDidLoad()

     let now = NSDate()
     let nowTimeStamp = self.getCurrentTimeStampWOMiliseconds(dateToConvert: now)

     // I save this dateToday as Key in Firebase
     dateToday = nowTimeStamp
}


func getCurrentTimeStampWOMiliseconds(dateToConvert: NSDate) -> String {
    let objDateformat: DateFormatter = DateFormatter()
    objDateformat.dateFormat = "yyyy-MM-dd"
    let strTime: String = objDateformat.string(from: dateToConvert as Date)
    let objUTCDate: NSDate = objDateformat.date(from: strTime)! as NSDate
    let milliseconds: Int64 = Int64(objUTCDate.timeIntervalSince1970)
    let strTimeStamp: String = "\(milliseconds)"
    return strTimeStamp
}

But when I convert it back to date I get 2017-09-22 16:00:00 +0000, which is wrong because it is 23rd of September in my location.

What is the right code to use so that I can get the correct date timestamp and time timestamp?

This question is related to ios swift date firebase timestamp

The answer is


For saving Current time to firebase database I use Unic Epoch Conversation:

let timestamp = NSDate().timeIntervalSince1970

and For Decoding Unix Epoch time to Date().

let myTimeInterval = TimeInterval(timestamp)
let time = NSDate(timeIntervalSince1970: TimeInterval(myTimeInterval))

If you just want the unix timestamp, create an extension:

extension Date {
    func currentTimeMillis() -> Int64 {
        return Int64(self.timeIntervalSince1970 * 1000)
    }
}

Then you can use it just like in other programming languages:

let timestamp = Date().currentTimeMillis()

First I would recommend you to store your timestamp as a NSNumber in your Firebase Database, instead of storing it as a String.

Another thing worth mentioning here, is that if you want to manipulate dates with Swift, you'd better use Date instead of NSDate, except if you're interacting with some Obj-C code in your app.

You can of course use both, but the Documentation states:

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

Now to answer your question, I think the problem here is because of the timezone.

For example if you print(Date()), as for now, you would get:

2017-09-23 06:59:34 +0000

This is the Greenwich Mean Time (GMT).

So depending on where you are located (or where your users are located) you need to adjust the timezone before (or after, when you try to access the data for example) storing your Date:

    let now = Date()

    let formatter = DateFormatter()

    formatter.timeZone = TimeZone.current

    formatter.dateFormat = "yyyy-MM-dd HH:mm"

    let dateString = formatter.string(from: now)

Then you have your properly formatted String, reflecting the current time at your location, and you're free to do whatever you want with it :) (convert it to a Date / NSNumber, or store it directly as a String in the database..)


The simple way to create Current TimeStamp. like below,

func generateCurrentTimeStamp () -> String {
    let formatter = DateFormatter()
    formatter.dateFormat = "yyyy_MM_dd_hh_mm_ss"
    return (formatter.string(from: Date()) as NSString) as String
}

in Swift 5

extension Date {
    static var currentTimeStamp: Int64{
        return Int64(Date().timeIntervalSince1970 * 1000)
    }
}

call like this:

let timeStamp = Date.currentTimeStamp
print(timeStamp)

Thanks @lenooh


If you code for iOS 13.0 or later and want a timestamp, then you can use:

let currentDate = NSDate.now

When we convert a UTC timestamp (2017-11-06 20:15:33 -08:00) into a Date object, the time zone is zeroed out to GMT. For calculating time intervals, this isn't an issue, but it can be for rendering times in the UI.

I favor the RFC3339 format (2017-11-06T20:15:33-08:00) for its universality. The date format in Swift is yyyy-MM-dd'T'HH:mm:ssXXXXX but RFC3339 allows us to take advantage of the ISO8601DateFormatter:

func getDateFromUTC(RFC3339: String) -> Date? {
    let formatter = ISO8601DateFormatter()
    return formatter.date(from: RFC3339)
}

RFC3339 also makes time-zone extraction simple:

func getTimeZoneFromUTC(RFC3339: String) -> TimeZone? {

    switch RFC3339.suffix(6) {

    case "+05:30":
        return TimeZone(identifier: "Asia/Kolkata")

    case "+05:45":
        return TimeZone(identifier: "Asia/Kathmandu")

    default:
        return nil

    }

}

There are 37 or so other time zones we'd have to account for and it's up to you to determine which ones, because there is no definitive list. Some standards count fewer time zones, some more. Most time zones break on the hour, some on the half hour, some on 0:45, some on 0:15.

We can combine the two methods above into something like this:

func getFormattedDateFromUTC(RFC3339: String) -> String? {

    guard let date = getDateFromUTC(RFC3339: RFC3339),
        let timeZone = getTimeZoneFromUTC(RFC3339: RFC3339) else {
            return nil
    }

    let formatter = DateFormatter()
    formatter.dateFormat = "h:mma EEE, MMM d yyyy"
    formatter.amSymbol = "AM"
    formatter.pmSymbol = "PM"
    formatter.timeZone = timeZone // preserve local time zone
    return formatter.string(from: date)

}

And so the string "2018-11-06T17:00:00+05:45", which represents 5:00PM somewhere in Kathmandu, will print 5:00PM Tue, Nov 6 2018, displaying the local time, regardless of where the machine is.

As an aside, I recommend storing dates as strings remotely (including Firestore which has a native date object) because, I think, remote data should agnostic to create as little friction between servers and clients as possible.


you can even create a function to return different time stamps depending on your necessity:

func dataatual(_ tipo:Int) -> String {
        let date = Date()
        let formatter = DateFormatter()
        if tipo == 1{
            formatter.dateFormat = "dd/MM/yyyy"
        } else if tipo == 2{
            formatter.dateFormat = "yyyy-MM-dd HH:mm"
        } else {
            formatter.dateFormat = "dd-MM-yyyy"
        }

        return formatter.string(from: date)
    } 

Questions with ios tag:

Adding a UISegmentedControl to UITableView Crop image to specified size and picture location Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Autoresize View When SubViews are Added Warp \ bend effect on a UIView? Speech input for visually impaired users without the need to tap the screen make UITableViewCell selectable only while editing Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64 iPhone is not available. Please reconnect the device Is it possible to opt-out of dark mode on iOS 13? Make a VStack fill the width of the screen in SwiftUI Presenting modal in iOS 13 fullscreen The iOS Simulator deployment targets is set to 7.0, but the range of supported deployment target version for this platform is 8.0 to 12.1 Xcode 10.2.1 Command PhaseScriptExecution failed with a nonzero exit code Xcode 10: A valid provisioning profile for this executable was not found Xcode 10, Command CodeSign failed with a nonzero exit code Command CompileSwift failed with a nonzero exit code in Xcode 10 How to format DateTime in Flutter , How to get current time in flutter? Xcode couldn't find any provisioning profiles matching How can I change the app display name build with Flutter? Convert Json string to Json object in Swift 4 Distribution certificate / private key not installed Get safe area inset top and bottom heights Error ITMS-90717: "Invalid App Store Icon" iOS Swift - Get the Current Local Time and Date Timestamp Xcode 9 Swift Language Version (SWIFT_VERSION) How do I use Safe Area Layout programmatically? Fixing Xcode 9 issue: "iPhone is busy: Preparing debugger support for iPhone" Cordova app not displaying correctly on iPhone X (Simulator) Detect if the device is iPhone X Xcode 9 error: "iPhone has denied the launch request" No signing certificate "iOS Distribution" found iOS 11, 12, and 13 installed certificates not trusted automatically (self signed) com.apple.WebKit.WebContent drops 113 error: Could not find specified service Safe Area of Xcode 9 How do you perform wireless debugging in Xcode 9 with iOS 11, Apple TV 4K, etc? What are my options for storing data when using React Native? (iOS and Android) Xcode Error: "The app ID cannot be registered to your development team." Open Url in default web browser Linker Command failed with exit code 1 (use -v to see invocation), Xcode 8, Swift 3 HTML5 Video autoplay on iPhone Swift error : signal SIGABRT how to solve it What is the meaning of 'No bundle URL present' in react-native? Convert NSDate to String in iOS Swift How can I regenerate ios folder in React Native project? `React/RCTBridgeModule.h` file not found Removing object from array in Swift 3 I get conflicting provisioning settings error when I try to archive to submit an iOS app

Questions with swift tag:

Make a VStack fill the width of the screen in SwiftUI Xcode 10.2.1 Command PhaseScriptExecution failed with a nonzero exit code Command CompileSwift failed with a nonzero exit code in Xcode 10 Convert Json string to Json object in Swift 4 iOS Swift - Get the Current Local Time and Date Timestamp Xcode 9 Swift Language Version (SWIFT_VERSION) How do I use Safe Area Layout programmatically? How can I use String substring in Swift 4? 'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator Safe Area of Xcode 9 The use of Swift 3 @objc inference in Swift 4 mode is deprecated? Swift error : signal SIGABRT how to solve it How to update the constant height constraint of a UIView programmatically? Convert NSDate to String in iOS Swift Waiting until the task finishes Type of expression is ambiguous without more context Swift Removing object from array in Swift 3 Date to milliseconds and back to date in Swift How does String substring work in Swift How does String.Index work in Swift Request Permission for Camera and Library in iOS 10 - Info.plist How to use addTarget method in swift 3 swift 3.0 Data to String? how to open an URL in Swift3 Get current date in Swift 3? Updating to latest version of CocoaPods? Swift programmatically navigate to another view controller/scene Correctly Parsing JSON in Swift 3 What is the 'open' keyword in Swift? Swift - How to detect orientation changes How to set Status Bar Style in Swift 3 how to make UITextView height dynamic according to text length? How to program a delay in Swift 3 How to set UICollectionViewCell Width and Height programmatically How can I mimic the bottom sheet from the Maps app? How do I write dispatch_after GCD in Swift 3, 4, and 5? How do I dispatch_sync, dispatch_async, dispatch_after, etc in Swift 3, Swift 4, and beyond? Default optional parameter in Swift function Swift: Display HTML data in a label or textView How to capture multiple repeated groups? How to pass data using NotificationCenter in swift 3.0 and NSNotificationCenter in swift 2.0? Convert string to date in Swift How to fix Error: this class is not key value coding-compliant for the key tableView.' Basic example for sharing text or image with UIActivityViewController in Swift Date Format in Swift How to display .svg image using swift How do I make a new line in swift 'Linker command failed with exit code 1' when using Google Analytics via CocoaPods Swift Error: Editor placeholder in source file Round up double to 2 decimal places How to make a UILabel clickable?

Questions with date tag:

How do I format {{$timestamp}} as MM/DD/YYYY in Postman? iOS Swift - Get the Current Local Time and Date Timestamp Typescript Date Type? how to convert current date to YYYY-MM-DD format with angular 2 SQL Server date format yyyymmdd Date to milliseconds and back to date in Swift Check if date is a valid one change the date format in laravel view page Moment js get first and last day of current month How can I convert a date into an integer? Moment.js - How to convert date string into date? Extract Month and Year From Date in R #1292 - Incorrect date value: '0000-00-00' Extract year from date Error in MySQL when setting default value for DATE or DATETIME How to Extract Year from DATE in POSTGRESQL Format date as dd/MM/yyyy using pipes Moment.js - tomorrow, today and yesterday Can I use an HTML input type "date" to collect only a year? Formatting a Date String in React Native How to initialize a variable of date type in java? How to properly add 1 month from now to current date in moment.js How to convert dd/mm/yyyy string into JavaScript Date object? Get only records created today in laravel Add A Year To Today's Date LocalDate to java.util.Date and vice versa simplest conversion? PHP date time greater than today Convert String to Carbon Moment Js UTC to Local Time HTML Display Current date Hive cast string to date dd-MM-yyyy moment.js, how to get day of week number How to convert an Instant to a date format? Oracle SQL - DATE greater than statement Python - Get Yesterday's date as a string in YYYY-MM-DD format Get date from input form within PHP How to force the input date format to dd/mm/yyyy? Format date and Subtract days using Moment.js How to add minutes to current time in swift How to convert Moment.js date to users local timezone? How to compare LocalDate instances Java 8 Getting Current date, time , day in laravel How can I parse / create a date time stamp formatted with fractional seconds UTC timezone (ISO 8601, RFC 3339) in Swift? Moment.js get day name from date Get current date in DD-Mon-YYY format in JavaScript/Jquery Getting the difference between two Dates (months/days/hours/minutes/seconds) in Swift How to convert a date to milliseconds Using momentjs to convert date to epoch then back to date Parsing date string in Go Java 8: Difference between two LocalDateTime in multiple units

Questions with firebase tag:

How can I solve the error 'TS2532: Object is possibly 'undefined'? Getting all documents from one collection in Firestore FirebaseInstanceIdService is deprecated Failed to resolve: com.google.firebase:firebase-core:16.0.1 NullInjectorError: No provider for AngularFirestore Firestore Getting documents id from collection How to update an "array of objects" with Firestore? firestore: PERMISSION_DENIED: Missing or insufficient permissions Cloud Firestore collection count iOS Swift - Get the Current Local Time and Date Timestamp Error: fix the version conflict (google-services plugin) Enabling CORS in Cloud Functions for Firebase Error: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() Plugin with id 'com.google.gms.google-services' not found Didn't find class "com.google.firebase.provider.FirebaseInitProvider"? How to use Apple's new .p8 certificate for APNs in firebase console Convert Promise to Observable How to add SHA-1 to android application how to end ng serve or firebase serve How do you send a Firebase Notification to all devices via CURL? Class file for com.google.android.gms.internal.zzaja not found No notification sound when sending notification from firebase in android How do I detect if a user is already logged in Firebase? FCM getting MismatchSenderId Firebase (FCM) how to get token How to handle notification when app in background in Firebase What is FCM token in Firebase? Is it safe to expose Firebase apiKey to the public? Firebase Permission Denied How can I send a Firebase Cloud Messaging notification without use the Firebase Console? Firebase onMessageReceived not called when app in background Firebase cloud messaging notification not received by device Where can I find the API KEY for Firebase Cloud Messaging? How to get a list of all files in Cloud Storage in a Firebase app? Notification Icon with the new Firebase Cloud Messaging system Unable to get provider com.google.firebase.provider.FirebaseInitProvider Failed to resolve: com.google.firebase:firebase-core:9.0.0 Firebase TIMESTAMP to date and Time how to get all child list from Firebase android Android Firebase, simply get one child object's data MongoDB vs Firebase Firebase: how to generate a unique numeric ID for key? Query based on multiple where clauses in Firebase How to delete/remove nodes on Firebase In Firebase, is there a way to get the number of children of a node without loading all the node data? Firebase Storage How to store and Retrieve images

Questions with timestamp tag:

concat yesterdays date with a specific time How do I format {{$timestamp}} as MM/DD/YYYY in Postman? iOS Swift - Get the Current Local Time and Date Timestamp Pandas: Convert Timestamp to datetime.date Spark DataFrame TimestampType - how to get Year, Month, Day values from field? What exactly does the T and Z mean in timestamp? What does this format means T00:00:00.000Z? Swift - iOS - Dates and times in different format Convert timestamp to string Timestamp with a millisecond precision: How to save them in MySQL Ping with timestamp on Windows CLI How to change default format at created_at and updated_at value laravel How to convert java.sql.timestamp to LocalDate (java8) java.time? How to get current timestamp in string format in Java? "yyyy.MM.dd.HH.mm.ss" How to parse/format dates with LocalDateTime? (Java 8) Get records of current month How to get correct timestamp in C# How to format current time using a yyyyMMddHHmmss format? Convert datetime to Unix timestamp and convert it back in python Python UTC datetime object's ISO format doesn't include Z (Zulu or Zero offset) How to get current timestamp in milliseconds since 1970 just the way Java gets How to format a java.sql.Timestamp(yyyy-MM-dd HH:mm:ss.S) to a date(yyyy-MM-dd HH:mm:ss) Function to convert timestamp to human date in javascript java.util.Date format SSSSSS: if not microseconds what are the last 3 digits? When is a timestamp (auto) updated? Java: Convert String to TimeStamp best practice to generate random token for forgot password Getting date format m-d-Y H:i:s.u from milliseconds How to get the unix timestamp in C# SQL Server 2008 Row Insert and Update timestamps Create timestamp variable in bash script Convert java.util.date default format to Timestamp in Java Using current time in UTC as default value in PostgreSQL How to convert UTC timestamp to device local time in android How to select rows that have current day's timestamp? How to have an automatic timestamp in SQLite? How do I convert dmesg timestamp to custom date format? Getting a timestamp for today at midnight? DB2 Timestamp select statement How to convert TimeStamp to Date in Java? How do I get the unix timestamp in C as an int? MySQL convert date string to Unix timestamp '0000-00-00 00:00:00' can not be represented as java.sql.Timestamp error How to convert from java.sql.Timestamp to java.util.Date? SQL Server: Cannot insert an explicit value into a timestamp column Getting time and date from timestamp with php How to convert integer timestamp to Python datetime What does the 'Z' mean in Unix timestamp '120314170138Z'? CURRENT_TIMESTAMP in milliseconds How do I automatically update a timestamp in PostgreSQL