How will I convert this datetime from the date?
From this: 2016-02-29 12:24:26
to: Feb 29, 2016
So far, this is my code and it returns a nil value:
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
dateFormatter.timeZone = NSTimeZone(name: "UTC")
let date: NSDate? = dateFormatter.dateFromString("2016-02-29 12:24:26")
print(date)
This may be useful for who want to use dateformatter.dateformat;
if you want 12.09.18 you use dateformatter.dateformat = "dd.MM.yy"
Wednesday, Sep 12, 2018 --> EEEE, MMM d, yyyy
09/12/2018 --> MM/dd/yyyy
09-12-2018 14:11 --> MM-dd-yyyy HH:mm
Sep 12, 2:11 PM --> MMM d, h:mm a
September 2018 --> MMMM yyyy
Sep 12, 2018 --> MMM d, yyyy
Wed, 12 Sep 2018 14:11:54 +0000 --> E, d MMM yyyy HH:mm:ss Z
2018-09-12T14:11:54+0000 --> yyyy-MM-dd'T'HH:mm:ssZ
12.09.18 --> dd.MM.yy
10:41:02.112 --> HH:mm:ss.SSS
Here are alternatives:
Era: G (AD), GGGG (Anno Domini)
Year: y (2018), yy (18), yyyy (2018)
Month: M, MM, MMM, MMMM, MMMMM
Day of month: d, dd
Day name of week: E, EEEE, EEEEE, EEEEEE
You have to declare 2 different NSDateFormatters, the first to convert the string to a NSDate and the second to print the date in your format.
Try this code:
let dateFormatterGet = NSDateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd HH:mm:ss"
let dateFormatterPrint = NSDateFormatter()
dateFormatterPrint.dateFormat = "MMM dd,yyyy"
let date: NSDate? = dateFormatterGet.dateFromString("2016-02-29 12:24:26")
print(dateFormatterPrint.stringFromDate(date!))
Swift 3 and higher:
From Swift 3 NSDate class has been changed to Date and NSDateFormatter to DateFormatter.
let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd HH:mm:ss"
let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "MMM dd,yyyy"
if let date = dateFormatterGet.date(from: "2016-02-29 12:24:26") {
print(dateFormatterPrint.string(from: date))
} else {
print("There was an error decoding the string")
}
Swift - 5.0
let date = Date()
let format = date.getFormattedDate(format: "yyyy-MM-dd HH:mm:ss") // Set output format
extension Date {
func getFormattedDate(format: String) -> String {
let dateformat = DateFormatter()
dateformat.dateFormat = format
return dateformat.string(from: self)
}
}
Swift - 4.0
2018-02-01T19:10:04+00:00 Convert Feb 01,2018
extension Date {
static func getFormattedDate(string: String , formatter:String) -> String{
let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "MMM dd,yyyy"
let date: Date? = dateFormatterGet.date(from: "2018-02-01T19:10:04+00:00")
print("Date",dateFormatterPrint.string(from: date!)) // Feb 01,2018
return dateFormatterPrint.string(from: date!);
}
}
Swift 3 and higher
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
dateFormatter.timeStyle = .none
dateFormatter.locale = Locale.current
print(dateFormatter.string(from: date)) // Jan 2, 2001
This is also helpful when you want to localize your App. The Locale(identifier: ) uses the ISO 639-1 Code.
See also the Apple Documentation
Swift 3 version with the new Date object instead NSDate:
let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd HH:mm:ss"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM dd,yyyy"
let date: Date? = dateFormatterGet.date(from: "2017-02-14 17:24:26")
print(dateFormatter.string(from: date!))
EDIT: after mitul-nakum suggestion
Convert #BatyrCan answer to Swift 5.3 with extra formats. Tested in Xcode 12.
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm:ss"
var dateFromStr = dateFormatter.date(from: "12:16:45")!
dateFormatter.dateFormat = "hh:mm:ss a 'on' MMMM dd, yyyy"
//Output: 12:16:45 PM on January 01, 2000
dateFormatter.dateFormat = "E, d MMM yyyy HH:mm:ss Z"
//Output: Sat, 1 Jan 2000 12:16:45 +0600
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
//Output: 2000-01-01T12:16:45+0600
dateFormatter.dateFormat = "EEEE, MMM d, yyyy"
//Output: Saturday, Jan 1, 2000
dateFormatter.dateFormat = "MM-dd-yyyy HH:mm"
//Output: 01-01-2000 12:16
dateFormatter.dateFormat = "MMM d, h:mm a"
//Output: Jan 1, 12:16 PM
dateFormatter.dateFormat = "HH:mm:ss.SSS"
//Output: 12:16:45.000
dateFormatter.dateFormat = "MMM d, yyyy"
//Output: Jan 1, 2000
dateFormatter.dateFormat = "MM/dd/yyyy"
//Output: 01/01/2000
dateFormatter.dateFormat = "hh:mm:ss a"
//Output: 12:16:45 PM
dateFormatter.dateFormat = "MMMM yyyy"
//Output: January 2000
dateFormatter.dateFormat = "dd.MM.yy"
//Output: 01.01.00
//Customisable AP/PM symbols
dateFormatter.amSymbol = "am"
dateFormatter.pmSymbol = "Pm"
dateFormatter.dateFormat = "a"
//Output: Pm
// Usage
var timeFromDate = dateFormatter.string(from: dateFromStr)
print(timeFromDate)
swift 3
let date : Date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM dd, yyyy"
let todaysDate = dateFormatter.string(from: date)
I solved my problem to the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'(e.g 2018-06-15T00:00:00.000Z) with this:
func formatDate(date: String) -> String {
let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
dateFormatter.timeStyle = .none
// dateFormatter.locale = Locale(identifier: "en_US") //uncomment if you don't want to get the system default format.
let dateObj: Date? = dateFormatterGet.date(from: date)
return dateFormatter.string(from: dateObj!)
}
iOS 15.0+
iPadOS 15.0+,
macOS 12.0+,
Mac Catalyst 15.0+,
tvOS 15.0+,
watchOS 8.0+,
Xcode 13.0+
Use formatted(date:time:)
let now = Date.now
let date = now.formatted(date: .abbreviated, time: .omitted)
Instead of .abbreviated, you may use another DateStyle such as .long, .numeric or define a custom format.
SwiftUI
Text(myDate, format: Date.FormatStyle(date: .numeric, time: .omitted))
or simply use:
Text(myDate, style: .date)
Reference
formatted(date:time:)
init(_:format:)
Text.DateStyle
Swift 4, 4.2 and 5
func getFormattedDate(date: Date, format: String) -> String {
let dateformat = DateFormatter()
dateformat.dateFormat = format
return dateformat.string(from: date)
}
let formatingDate = getFormattedDate(date: Date(), format: "dd-MMM-yyyy")
print(formatingDate)
Swift Version: 5.6 + Above
DateFormatter’s dateFormatter property is used to format Date with a custom String Pattern.
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM dd, yyyy"
let date = dateFormatter.string(from: datePicker.date)
print(date)
//Feb 28, 2022
If you want anything that shouldn’t be formatted and printed, then use single quotes around that word. Like; ‘at’
dateFormatter.dateFormat = "MMM dd, yyyy 'at' hh:MM a"
// May 29, 2022 at 12:05 PM
These are all possible Patterns to Format Date, Time & Time Zone.
Swift 3 with a Date extension
extension Date {
func string(with format: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
return dateFormatter.string(from: self)
}
}
Then you can use it like so:
let date = Date()
date.string(with: "MMM dd, yyyy")
If you want to parse date from "1996-12-19T16:39:57-08:00", use the following format "yyyy-MM-dd'T'HH:mm:ssZZZZZ":
let RFC3339DateFormatter = DateFormatter()
RFC3339DateFormatter.locale = Locale(identifier: "en_US_POSIX")
RFC3339DateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
RFC3339DateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
/* 39 minutes and 57 seconds after the 16th hour of December 19th, 1996 with an offset of -08:00 from UTC (Pacific Standard Time) */
let string = "1996-12-19T16:39:57-08:00"
let date = RFC3339DateFormatter.date(from: string)
from Apple https://developer.apple.com/documentation/foundation/dateformatter
Another interessant possibility of format date. This screenshot belongs to Apple's App "News".
Here is the code:
let dateFormat1 = DateFormatter()
dateFormat1.dateFormat = "EEEE"
let stringDay = dateFormat1.string(from: Date())
let dateFormat2 = DateFormatter()
dateFormat2.dateFormat = "MMMM"
let stringMonth = dateFormat2.string(from: Date())
let dateFormat3 = DateFormatter()
dateFormat3.dateFormat = "dd"
let numDay = dateFormat3.string(from: Date())
let stringDate = String(format: "%#\n%# %#", stringDay.uppercased(), stringMonth.uppercased(), numDay)
Nothing to add to alternative proposed by lorenzoliveto. It's just perfect.
let dateFormat = DateFormatter()
dateFormat.dateFormat = "EEEE\nMMMM dd"
let stringDate = dateFormat.string(from: Date()).uppercased()
import UIKit
// Example iso date time
let isoDateArray = [
"2020-03-18T07:32:39.88Z",
"2020-03-18T07:32:39Z",
"2020-03-18T07:32:39.8Z",
"2020-03-18T07:32:39.88Z",
"2020-03-18T07:32:39.8834Z"
]
let dateFormatterGetWithMs = DateFormatter()
let dateFormatterGetNoMs = DateFormatter()
// Formater with and without millisecond
dateFormatterGetWithMs.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
dateFormatterGetNoMs.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"
let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "MMM dd,yyyy"
for dateString in isoDateArray {
var date: Date? = dateFormatterGetWithMs.date(from: dateString)
if (date == nil){
date = dateFormatterGetNoMs.date(from: dateString)
}
print("===========>",date!)
}
just use below function to convert date format:-
let convertedFormat = convertToString(dateString: "2019-02-12 11:23:12", formatIn: "yyyy-MM-dd hh:mm:ss", formatOut: "MMM dd, yyyy") //calling function
print(convertedFormat) // feb 12 2019
func convertToString (dateString: String, formatIn : String, formatOut : String) -> String {
let dateFormater = DateFormatter()
dateFormater.timeZone = NSTimeZone(abbreviation: "UTC") as TimeZone!
dateFormater.dateFormat = formatIn
let date = dateFormater.date(from: dateString)
dateFormater.timeZone = NSTimeZone.system
dateFormater.dateFormat = formatOut
let timeStr = dateFormater.string(from: date!)
return timeStr
}
To convert 2016-02-29 12:24:26 into a date, use this date formatter:
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss"
Edit: To get the output Feb 29, 2016 use this date formatter:
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MMM dd, yyyy"
For Swift 4.2, 5
Pass date and format as whatever way you want.
To choose format you can visit, NSDATEFORMATTER website:
static func dateFormatter(date: Date,dateFormat:String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = dateFormat
return dateFormatter.string(from: date)
}
Place it in extension and call it like below. It's easy to use throughout the application.
self.getFormattedDate(strDate: "20-March-2019", currentFomat: "dd-MMM-yyyy", expectedFromat: "yyyy-MM-dd")
Implementation
func getFormattedDate(strDate: String , currentFomat:String, expectedFromat: String) -> String{
let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = currentFomat
let date : Date = dateFormatterGet.date(from: strDate) ?? Date()
dateFormatterGet.dateFormat = expectedFromat
return dateFormatterGet.string(from: date)
}
From iOS 15 use something like this:
extension Date {
var string: String {
if #available(iOS 15.0, *) {
return self.formatted(date: .complete, time: .complete)
} else {
return self.description
}
}
}
Here is a full date format extension for swift
extension Date {
func getFormattedDate(format: String) -> String {
let dateformat = DateFormatter()
dateformat.dateFormat = format
return dateformat.string(from: self)
}
func getFormattedDate(style: DateFormatter.Style) -> String {
let dateformat = DateFormatter()
dateformat.dateStyle = style
return dateformat.string(from: self)
}
}
Usage
myDate.getFormattedDate(style: .medium) //medium, short, full, long
OR
myDate.getFormattedDate(format: "yyyy/MM/dd HH:mm:ss")
swift 3
func dataFormat(dataJ: Double) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .long
dateFormatter.timeStyle = .none
let date = Date(timeIntervalSince1970: dataJ)
return (dataJ != nil) ? "Today, \(dateFormatter.string(from: date))" : "Date Invalid"
}
I recommend to add timezone by default. I will show an example for swift 5
1. new an extension file Date+Formatter.swift
import Foundation
extension Date {
func getFormattedDateString(format: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
dateFormatter.timeZone = TimeZone.current
return dateFormatter.string(from: self)
}
}
Usage example
let date = Date()
let dateString = date.getFormattedDateString(format: "yyyy-MM-dd HH:mm:ss")
print("dateString > \(dateString)")
// print
// dateString > 2020-04-30 15:15:21
class Utils {
class func dateFormatter(_ date: Date, _ format: String) -> String {
let dateformat = DateFormatter()
dateformat.dateFormat = format
return dateformat.string(from: date)
}
}
print(Utils.dateFormatter(Date(), "EEEE, MMM d, yyyy"))
Create class name Utils import same function and you can use globally accesss any where with your date and formate
I want to convert server UTC time to local time and vice-versa.
Here is my code..
var isTimeFromServer = true
var time:String!
var period:String!
let timeString = "6:59 AM" //Current UTC time
if isTimeFromServer {
let index = timeString.index(timeString.startIndex, offsetBy: 5)
let twelve = timeString.substring(to: index)
var dateString:String!
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "H:mm"
let date12 = dateFormatter.date(from: twelve)!
dateFormatter.dateFormat = "h:mm a"
let date22 = dateFormatter.string(from: date12)
//print(date22)
dateString = date22
//print("dateString=\(dateString)")
time = dateString.components(separatedBy: " ")[0]
period = dateString.components(separatedBy: " ")[1]
}
else {
time = timeString.components(separatedBy: " ")[0]
period = timeString.components(separatedBy: " ")[1]
}
var hour = Int(time.components(separatedBy: ":")[0])
hour = period == "AM" ? hour : hour! + 12
let minute = Int(time.components(separatedBy: ":")[1])
let calender = NSCalendar.current
var datecomponent = DateComponents()
datecomponent.calendar = calender
datecomponent.hour = hour
datecomponent.minute = minute
if !isTimeFromServer {
// local to UTC
datecomponent.timeZone = TimeZone.current
}
else {
datecomponent.timeZone = TimeZone(abbreviation: "UTC")
}
let date = datecomponent.date
let dateFormatter = DateFormatter()
if !isTimeFromServer {
dateFormatter.dateFormat = "H:mm"
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
dateFormatter.string(from: date!)
}
else {
//UTC to local
dateFormatter.dateFormat = "h:mm a"
dateFormatter.timeZone = TimeZone.current
dateFormatter.string(from: date!)
}
I get the local time
o/p: "12:52 PM"
But actual local time and output time difference is 23 minutes.
I don't know what's wrong with your code.But looks too much unnecessary things are there like you're setting calendar, fetching some elements from string.
Here is my small version of UTCToLocal and localToUTC function. But for that you need to pass string in specific format. Cause I've forcly unwrapped date objects. But you can use some guard conditions to prevent crashing your app.
func localToUTC(dateStr: String) -> String? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "h:mm a"
dateFormatter.calendar = Calendar.current
dateFormatter.timeZone = TimeZone.current
if let date = dateFormatter.date(from: dateStr) {
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
dateFormatter.dateFormat = "H:mm:ss"
return dateFormatter.string(from: date)
}
return nil
}
func utcToLocal(dateStr: String) -> String? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "H:mm:ss"
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
if let date = dateFormatter.date(from: dateStr) {
dateFormatter.timeZone = TimeZone.current
dateFormatter.dateFormat = "h:mm a"
return dateFormatter.string(from: date)
}
return nil
}
and call these function like below.
print(utcToLocal(dateStr: "13:07:00"))
print(localToUTC(dateStr: "06:40 PM"))
Mrugesh's answer is perfect, but if someone need to use their own formats, or in some different format, I've generalised it so you can give different format or same in both parameters.
func localToUTC(date:String, fromFormat: String, toFormat: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = fromFormat
dateFormatter.calendar = NSCalendar.current
dateFormatter.timeZone = TimeZone.current
dateFormatter.date
let dt = dateFormatter.date(from: date)
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
dateFormatter.dateFormat = toFormat
return dateFormatter.string(from: dt!)
}
func UTCToLocal(date:String, fromFormat: String, toFormat: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = fromFormat
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
let dt = dateFormatter.date(from: date)
dateFormatter.timeZone = TimeZone.current
dateFormatter.dateFormat = toFormat
return dateFormatter.string(from: dt!)
}
let localDateAsString = UTCToLocal(date: dateAsString!, fromFormat: "hh:mm a, dd MMM yyyy", toFormat: "hh:mm a, dd MMM yyyy")
You can use it as above. Hope it helps.
By the help of Mrugesh Tank Answer,
I have updated his answer and creating the extensions for the date. So that you can easily access the functions from anywhere either from ViewController or either from cell class as well.
extension String {
//MARK:- Convert UTC To Local Date by passing date formats value
func UTCToLocal(incomingFormat: String, outGoingFormat: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = incomingFormat
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
let dt = dateFormatter.date(from: self)
dateFormatter.timeZone = TimeZone.current
dateFormatter.dateFormat = outGoingFormat
return dateFormatter.string(from: dt ?? Date())
}
//MARK:- Convert Local To UTC Date by passing date formats value
func localToUTC(incomingFormat: String, outGoingFormat: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = incomingFormat
dateFormatter.calendar = NSCalendar.current
dateFormatter.timeZone = TimeZone.current
let dt = dateFormatter.date(from: self)
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
dateFormatter.dateFormat = outGoingFormat
return dateFormatter.string(from: dt ?? Date())
}
}
Example how to use it:-
Note:- eventStartDate is the string which you have to converted in your format like this:- "2018-07-11T16:22:00.000Z"
let finalDate = eventStartDate.UTCToLocal(incomingFormat: "yyyy-MM-dd'T'HH:mm:ss.SSSZ", outGoingFormat: "MMM d, yyyy h:mm a")
To convert a UTC Date to a local system date you could use the following Date extension:
extension Date {
// Convert local time to UTC (or GMT)
func toGlobalTime() -> Date {
let timezone = TimeZone.current
let seconds = -TimeInterval(timezone.secondsFromGMT(for: self))
return Date(timeInterval: seconds, since: self)
}
// Convert UTC (or GMT) to local time
func toLocalTime() -> Date {
// 1) Get the current TimeZone's seconds from GMT. Since I am in Chicago this will be: 60*60*5 (18000)
let timezoneOffset = TimeZone.current.secondsFromGMT()
// 2) Get the current date (GMT) in seconds since 1970. Epoch datetime.
let epochDate = self.timeIntervalSince1970
// 3) Perform a calculation with timezoneOffset + epochDate to get the total seconds for the
// local date since 1970.
// This may look a bit strange, but since timezoneOffset is given as -18000.0, adding epochDate and timezoneOffset
// calculates correctly.
let timezoneEpochOffset = (epochDate + Double(timezoneOffset))
// 4) Finally, create a date using the seconds offset since 1970 for the local date.
return Date(timeIntervalSince1970: timezoneEpochOffset)
}
}
For everyone using TimeZone objects.
I would advise you to create your TimeZone from identifier rather than abbreviation when you have the possibility.
This prevents errors caused by daylight saving.
To illustrate my point let's take an example.
You can instantiate like this
let timeZone = TimeZone(identifier: "Europe/Paris")
or like that
let timeZone = TimeZone(abbreviation: "CEST") or "UTC +2:00"
But this is time zone for summer CEST meaning Central Europe Summer Time
We have CET meaning Central Europe Time for winter which is "UTC +1:00"
You could manage daylight saving by your own with Date.isDaylightSavingsTime but this means more code and you don't have control on where your daylight saving sprang from.
"indicates whether the receiver is currently using daylight saving time" from official doc
All is that is to say favour TimeZone(identifier: ...)
You can use in swift 4/5
var myDate:String = "2020-02-18 14:30:57"
var convertedLocalTime:String = ""
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd H:mm:ss"
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
if let dt = dateFormatter.date(from: myDate) {
dateFormatter.timeZone = TimeZone.current
dateFormatter.dateFormat = "yyyy-MM-dd h:mm a"
convertedLocalTime = dateFormatter.string(from: dt)
} else {
print("There was an error decoding the string")
}
print("convertedLocalTime--",convertedLocalTime)
Please try it:
func convertUTCToLocal(timeString: String) -> String? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "h:mm a"
dateFormatter.timeZone = TimeZone.init(abbreviation: "UTC")
let timeUTC = dateFormatter.date(from: timeString)
if timeUTC != nil {
dateFormatter.timeZone = NSTimeZone.local
let localTime = dateFormatter.string(from: timeUTC!)
return localTime
}
return nil
}
func convertLocalToUTC(localTime: String) -> String? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "h:mm a"
dateFormatter.timeZone = NSTimeZone.local
let timeLocal = dateFormatter.date(from: localTime)
if timeLocal != nil {
dateFormatter.timeZone = TimeZone.init(abbreviation: "UTC")
let timeUTC = dateFormatter.string(from: timeLocal!)
return timeUTC
}
return nil
}
var isTimeFromServer = true
var time:String!
var period:String!
let timeString = "6:59 AM" //Current UTC time
if isTimeFromServer {
print(convertUTCToLocal(timeString: timeString))
} else {
print(convertLocalToUTC(localTime: timeString))
}
If you need to convert timestamp you can use timezoneOffset like here:
if let dateStr = model.date, let dateInt = Int(dateStr) {
let timezoneOffset = TimeZone.current.secondsFromGMT()
let localDateInt = dateInt + timezoneOffset
let date = Date(timeIntervalSince1970: Double(localDateInt))
cell.dateLbl.text = date.toShortDateTimeString()
}
Happy New Year, all!
How do I get a datePicker text to show like this Jan 1, 2017 instead of 2017/1/1? In my PlayGround, it looks as expected but in my simulator or console, it looks not expected.
// createDatePicker():
datePicker.datePickerMode = .date
// donePressed():
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .none
dateFormatter.dateFormat = "mm/dd/yyyy"
let fromString = dateFormatter.string(from: datePicker.date)
let date = dateFormatter.date(from: fromString) // I dont need time but got Jan 1, 2017, 12:00 AM in playground
datePickerText.text = "\(date)"
print("\(date)") // in console: Optional(2017-1-1 00:00:00 +0000)
I need to get rid of the Optional() but not sure how to convert Date! to String!. How to achieve getting the text to be Jan 1, 2017?
In your code you converting Date to date String: -
let fromString = dateFormatter.string(from: datePicker.date)
let date = dateFormatter.date(from: fromString) //Avoid this line in your code
then no need to change again date string into date try below code: -
let formatter = DateFormatter()
formatter.dateFormat = "MMM d, yyyy" //Date Formatting
let date = formatter.string(from: datePicker.date)
datePickerText.text = date
print(date)
Output:-
Jan 1, 2017
Just format your date how you want it to be, like this:
dateFormatter.dateFormat = "MMM d, yyyy"
let fromString = dateFormatter.string(from: datePicker.date)
print(fromString) // Jan 1, 2017
You can try this!
let formatter = NSDateFormatter()
formatter.dateformat = "MMMM dd,YYYY"
if there is any label to which your are trying to show the date format then,
label.text = formatter.stringFromDate(datepicker.date)
I've seen this post for other languages but not for swift. I have a date saved in the format of 2015-08-31 21:36:00 +0000 and I'm able to extract the day, month, year and weekday with the code below to produce Monday, August 31, 2015. When I try to use:
let hourInt = components.hour
var hourString = String(hourInt)
It prints a four hour difference. In this case "17" for the "21". How do I
display it as 9:36 P.M.?
let flags: NSCalendarUnit = NSCalendarUnit.CalendarUnitMinute | NSCalendarUnit.CalendarUnitHour | NSCalendarUnit.CalendarUnitDay | NSCalendarUnit.CalendarUnitWeekday | NSCalendarUnit.CalendarUnitMonth | NSCalendarUnit.CalendarUnitYear
let date = NSDate()
let dateFormatter: NSDateFormatter = NSDateFormatter()
let components = NSCalendar.currentCalendar().components(flags, fromDate: array.date)
let weekday = components.weekday
let weekdays = dateFormatter.weekdaySymbols
let weekdayString = weekdays[weekday-1] as! String
let month = components.month
let months = dateFormatter.monthSymbols
let monthString = months[month-1] as! String
let dayInt = components.day
var dayString = String(dayInt)
let year = components.year
let yearString = String(year)
println(weekdayString + ", " + monthString + " " + dayString + ", " + yearString)
Your date string suffix +0000 means it is UTC time if you want to display time at UTC you need to specify it when setting your date formatter.
let dateString = "2015-08-31 21:36:00 +0000"
let df = NSDateFormatter()
df.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
if let date = df.dateFromString(dateString) {
// now you have your date object
// to display UTC time you have to specify timeZOne UTC
df.timeZone = NSTimeZone(forSecondsFromGMT: 0)
df.dateFormat = "EEEE, MMMM dd, yyyy h:mm:ss a"
let stringFromDate = df.stringFromDate(date)
println(stringFromDate) // "Monday, August 31, 2015 9:36:00 PM"
}
If you want to strip the time zone information, pass the GMT time zone.
This code does quite the same as yours
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "EEEE, MMMM dd, yyyy"
dateFormatter.timeZone = NSTimeZone(abbreviation: "GMT")
println(dateFormatter.stringFromDate(array.date))
Setting locale of NSDateFormatter to en_US_POSIX fixed issue for me.
let sharedFormatter:NSDateFormatter = {
let formatter = NSDateFormatter()
formatter.locale = NSLocale(localeIdentifier:"en_US_POSIX")
return formatter
}()
sharedFormatter.dateFormat = "MMM d YYYY, h:mm a"
let dateString = sharedFormatter.stringFromDate(NSDate())
// Aug 2 2016, 5:45 PM
Swift 5.0
let dateString = "2015-08-31 21:36:00 +0000"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
if let date = dateFormatter.date(from: dateString) {
// now you have your date object
// to display UTC time you have to specify timeZOne UTC
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
dateFormatter.dateFormat = "EEEE, MMMM dd, yyyy h:mm:ss a"
let stringFromDate = dateFormatter.string(from: date)
print(stringFromDate) // "Monday, August 31, 2015 9:36:00 PM"
}