Swift tutorial: Convert local Date to UTC

Convert Date in local timezone to UTC in Swift - Tutorial

In this tutorial, we will learn how to convert a date in local timezone to date in UTC timezone using swift language for iOS SDK. We will pass the local date to the function and that function will return the converted date in UTC timezone. So let us start the tutorial and learn how to convert a local timzone date to UTC timezone date in swift for iOS app development.

Step1: Create a function named “convertToUTC“, which will accept a string parameter and that is the date we want to convert into UTC timezone and returns the converted date in UTC timezone as a string.

Step2: We will create a “DateFormatter” that has a date format “dd-MM-yyyy hh:mm a“. You can change this date format as per your requirements.

Step3: Finally, we convert the local timezone date (passed as string object), to Date object and then set our “DateFormatter“, time zone to “UTC“. Lastly, convert the Date object to string object and return from the function.

Step 4: Now call our function and printing the output in console. Here, we need to pass date in exact date format as set to our “DateFormatter” object otherwise the Date object will comes as nil.

Step 5: Run the code, and you will see the output in your console. My device timezone is IST i.e UTC + 5:30 , so i get the output as

Converted Date == 16-09-2017 05:30 AM

Final conclusion: In this tutorial, you learned how to convert date in device local timezone to UTC timezone in swift language.

You can also download the source code from the link
ConvertDateToUTC-Tutorial.zip

1 thought on “Swift tutorial: Convert local Date to UTC”

  1. Pingback: Get array of time interval slots between two dates - iOSTutorialJunction

Comments are closed.