Convert date in local timezone to UTC:
In this tutorial, we will learn how to convert a date in local timezone to date in UTC timezone in swift. We will pass the date to the function (we will create it in this tutorial) and it will return the date converted to UTC timezone. So let us start the tutorial and learn how to convert a date to UTC date in swift.
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