swift my current time varibale isnt showing my actual current time - swift

So here is my issue, when i try to find my current date and time, it gives me a time 7hrs ahead of my actual time. Example actual current time= 1pm, xcode current time 8pm. I would like to get the current time in the timezone of the user. any suggestions?
ok let me rephrase what Im asking. I have managed to convert the parsed endDate into a date. I know how to get the current date using NSDate, but it is NOT the right time. How can i change that time to the correct time? Please use a step by step plan, so i know how to handle this in the future. Thanks for all your input!
// get end date
let DateEnd = object.objectForKey("Ends") as! String
let currentDate = NSDate()
let dateFormatter = NSDateFormatter()
dateFormatter.timeZone = NSTimeZone(name: "UTC")
//dateFormatter.timeZone = NSTimeZone(name: "GMT")
dateFormatter.dateFormat = "MM/dd/yy, hh:mm a"
let date = dateFormatter.dateFromString(parseDateEnd)
print(date)
print(currentDate)

NSDate always store its data in UTC. Whatever timezone you want to convert to, you have to tell your dateFormatter to do that. Also, if you do print(currentDate), it will always display time in UTC. You have to format it first.
let dateFormatter = NSDateFormatter()
dateFormatter.timeZone = NSTimeZone.defaultTimeZone()
dateFormatter.dateFormat = "MM/dd/yy, hh:mm a"
let currentDate = NSDate()
print(currentDate) // 2015-11-13 22:02:09 +0000
print(dateFormatter.stringFromDate(currentDate)) // 11/13/15, 05:02 PM
My timezone is EST (-05:00). My guess is you are in the -07:00 timezone.
There's nothing wrong with your Swift or Xcode. It's all about time in different timezones. As example, let's say it is:
9pm in Chicago (UTC -05:00)
2am in London (UTC +00:00) ← this is what NSDate() would return
4am in Istanbul (UTC +02:00).
They represent the same moment in time, but different clock positions based on where you are. At this time of the year, UTC = GMT = London's time. If you are to call NSDate(), it will always return time in UTC, regardless of where you are. So you will get 2am.
To get your local time, you have to format it into your timezone. The default timezone for the dateFormatter is UTC. Hence, you must change that into your local timezone by:
dateFormatter.timeZone = NSTimeZone.defaultTimeZone()

let dateFormatter = NSDateFormatter()
NSTimeZone.defaultTimeZone()
dateFormatter.timeZone = NSTimeZone.defaultTimeZone()
dateFormatter.timeStyle = .LongStyle
dateFormatter.dateStyle = .ShortStyle
let currentDate = NSDate()
dateFormatter.stringFromDate(currentDate)
print(currentDate)
/* prints your Zulu time with POSIX format
2015-11-14 01:48:30 +0000
*/
print(dateFormatter.stringFromDate(currentDate))
/* prints your localized version
* localized date and time with your time offset
* as is preset in your computer
14/11/15 02:49:13 GMT+1
/*
....
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: "")
dateFormatter.timeStyle = .LongStyle
dateFormatter.dateStyle = .ShortStyle
if let dateFromString = dateFormatter.dateFromString("2015-11-14 08:10:15 GMT-7") {
print(dateFromString)
// print
// 2015-11-14 15:10:15 +0000
//
//
// 2015-11-14 15:10:15 +0000 == 2015-11-14 08:10:15 GMT-7
//
//
}
to compare the dates
let date1 = dateFormatter.dateFromString("2015-11-14 08:10:15 GMT-7")
let date2 = dateFormatter.dateFromString("2015-11-14 15:10:15 +0000")
if let date1 = date1, let date2 = date2 {
date1.compare(date2) == NSComparisonResult.OrderedSame // true !!!
}
.. time difference
let date1 = dateFormatter.dateFromString("2015-11-14 01:10:15 GMT-7")
let date2 = dateFormatter.dateFromString("2015-11-14 15:10:15 +0000")
if let date1 = date1, let date2 = date2 {
date1.compare(date2) == NSComparisonResult.OrderedSame // false !
date1.timeIntervalSince1970 - date2.timeIntervalSince1970 == -25200 // true
date1.timeIntervalSinceDate(date2) == -25200 // true
// the difference is in secons ( 7 hours * 3600 = 25200 seconds
}
... the same data, other form of time string, manually set time offset
dateFormatter.dateStyle = .NoStyle
dateFormatter.timeStyle = .MediumStyle
dateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: -7*3600) // GMT-7
let date1 = dateFormatter.dateFromString("01:10:15")
dateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0*3600) // GMT+0
let date2 = dateFormatter.dateFromString("15:10:15")
if let date1 = date1, let date2 = date2 {
date1.compare(date2) == NSComparisonResult.OrderedSame // false !
date1.timeIntervalSince1970 - date2.timeIntervalSince1970 == -25200 // true
date1.timeIntervalSinceDate(date2) == -25200 // true
// the difference is in secons ( 7 hours * 3600 = 25200 seconds
}
... what is now the date1 and date2 ????
print(date1!) // 2000-01-01 08:10:15 +0000
print(date2!) // 2000-01-01 15:10:15 +0000

Related

Date from String in Swift but it becomes the previous day

I am trying to create a day from a string (mSince) :
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let newDate = dateFormatter.date(from:mSince as! String)!
and the print values are:
mSince = Optional(2021-04-25)
newDate = 2021-04-24 21:00:00 +0000
I could not figure out why newDate becomes the previous day.
Thank you!
Below is an example of how to create dates from multiple UTC timezones and an example of how to get the delta (in seconds) between the dates:
extension Date {
static func - (lhs: Date, rhs: Date) -> TimeInterval {
return lhs.timeIntervalSinceReferenceDate - rhs.timeIntervalSinceReferenceDate
}
}
let utcDateFormatter = DateFormatter()
utcDateFormatter.dateStyle = .medium
utcDateFormatter.timeStyle = .medium
// Set the timeZone to the device’s local time zone.
utcDateFormatter.timeZone = TimeZone(abbreviation: "UTC")
let date1 = Date()
print(utcDateFormatter.string(from: date1))
// Parsing a string date
let dateString1 = "May 11, 2020 at 4:23:11 AM"
let utcDate1 = utcDateFormatter.date(from: dateString1)
// Set a date for a different timeZone (2 hours difference)
utcDateFormatter.timeZone = TimeZone(secondsFromGMT: 3600)
// Printing a Date
let date2 = Date()
print(utcDateFormatter.string(from: date2))
// Parsing a string representing a date
let dateString2 = "May 11, 2020 at 4:23:11 AM"
let utcDate2 = utcDateFormatter.date(from: dateString2)
let diff = utcDate1! - utcDate2!
print(diff)

Date not convert in AM/PM Format in swift

I need to date and time with my own format like time in AM/PM (12 hours).
extension Date {
func getStringFromDateWithUTCFormat() -> ObjTimeStamp {
let dateFormatterPrint = DateFormatter()
dateFormatterPrint.timeZone = TimeZone.init(abbreviation: "UTC")
// Get Date
dateFormatterPrint.dateFormat = "MM/dd/yyyy" //"MMM dd,yyyy"
let date = dateFormatterPrint.string(from: self)
// Get Time
dateFormatterPrint.dateFormat = "hh:mm:ss a"
let time = dateFormatterPrint.string(from: self)
return ObjTimeStamp.init(date: date, time: time, timeStamp: self)
}
}
Update
Calling function
self.currentDate = Date()
let objTimeStamp = currentDate.getStringFromDateWithUTCFormat()
Perfect work when device time in 12-hour format when I try to change device time in 24-hour formate then given wrong time format.
set your dateFormatter locale to en-US then try to convert, it's works for me when iPhone's time format is 24 hour:
let date = Date()
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en-US")
formatter.dateFormat = "hh:mm a"
let time12 = formatter.string(from: date)
print(time12)
output:
01:37 PM

Convert time string to Unix time date of the same day

how to convert a string hour to millisecond of the day?
for exemple:
let strDate = "06:00 PM"
Or:
let strDate = "09:00 AM"
my code:
let dateString = "06:00 PM"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm"
guard let date = dateFormatter.date(from: dateString)
else { fatalError() }
print(date)
for example my string is: 06:00 PM, so I want to have the date in millisecond of today Thursday 20 September 2018 at 06:00 PM
You can set your DateFormatter default date to startOfDay for today, set the formatter locale locale to "en_US_POSIX" when parsing your time then you can simply get your resulting date timeIntervalSince1970 and multiply by 1000:
let strTime = "06:00 PM"
let formatter = DateFormatter()
formatter.defaultDate = Calendar.current.startOfDay(for: Date())
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "hh:mm a"
if let date = formatter.date(from: strTime) {
let milliseconds = date.timeIntervalSince1970 * 1000
print(milliseconds) // 1537477200000
let date2 = Date(timeIntervalSince1970: milliseconds/1000)
print(date2.description(with: .current)) // Thursday, September 20, 2018 at 6:00:00 PM Brasilia Standard Time
}
First, you need to parse the date string:
let dateString = "06:00 PM"
let formatter = DateFormatter()
formatter.defaultDate = Date()
formatter.dateFormat = "hh:mm a"
formatter.locale = Locale(identifier: "en_US_POSIX")
let date = formatter.date(from: dateString)
Then, you need to get the start of day:
let calendar = Calendar.current
let start = calendar.startOfDay(for: date)
After that, get the time interval between date and start:
let timeInterval = date.timeIntervalSince(start)
let milliseconds = timeInterval * 1000.0

Using DateFormatter with TimeZone to format dates in Swift

How can I parse a date that has only date information (without time), like 2018-07-24
Im trying with
let dateFormatter = DateFormatter()
dateFormat.dateFormat = "yyyy-MM-dd"
dateFormatter.dateFormat = dateFormat
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
dateFormatter.date(from: "2018-07-24")
prints day 23
It looks like it uses 00:00:00 as default time and then transform it into UTC results into the day before...
How can I change that?
Seems that you set time zone for formatter to UTC but then try to get the day in your local time zone.
If you use this code - you will see the 24-th day
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
let date = dateFormatter.date(from: "2018-07-24")
print(dateFormatter.string(from: date!)) // prints "2018-07-24"
But if you use "Calendar" to get the day component from the date you will get the day with your timeZone offset.
So for example in my time zone I see the 24th day (GMT+02) using this code
var calendar = Calendar.current
let day = calendar.component(.day, from: date!)
print(day) // prints 24
But if I set the time zone for calendar somewhere in USA I see the 23rd day
var calendar = Calendar.current
calendar.timeZone = TimeZone.init(abbreviation: "MDT")!
let day = calendar.component(.day, from: date!)
print(day) // prints 23
So the calendar uses your local time zone to get the component from date
So if you need to get the day component from date use the same time zone you used to parse the date from string.
var calendar = Calendar.current
calendar.timeZone = TimeZone(abbreviation: "UTC")!
let day = calendar.component(.day, from: date!)
print(day) // prints 24

UTC to local time conversion not working in Swift 2

I am trying to convert a UTC time to local timezone, but it doesn't seem to be converting it at all:
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let date1 = dateFormatter.dateFromString(dateStringFromServer)!
dateFormatter.timeZone = NSTimeZone.localTimeZone()
let date2 = dateFormatter.dateFromString(dateStringFromServer)!
The dateStringFromServer is a string representation of a UTC date. So I was expecting date1 to be in UTC, and date2 to be in PDT (my local time zone), but they are both the same. Something wrong with my syntax?
This is what I'm getting:
dateStringFromServer: 2016-10-21T05:24:26.000Z
date1: 2016-10-21 05:24:26 +0000
date2: 2016-10-21 05:24:26 +0000
How can I get date2 be in the device's local timezone?
If you want to convert to the time zone set on the device you can do this
Swift3
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let date1 = dateFormatter.date(from: dateStringFromServer)
// return the timeZone of your device i.e. America/Los_angeles
let timeZone = TimeZone.autoupdatingCurrent.identifier as String
dateFormatter.timeZone = TimeZone(identifier: timeZone)
let date2 = dateFormatter.string(from: date1)
Swift2
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let date1 = dateFormatter.dateFromString(dateStringFromServer)
// return the timeZone of your device i.e. America/Los_angeles
let timeZone = NSTimeZone.localTimeZone().name
dateFormatter.timeZone = NSTimeZone(name: timeZone)
let date2 = dateFormatter.stringFromDate(date1!)
It's the same because even though you think you're setting the date formatter's time zone to the current time zone after setting the first date, it doesn't matter. If you don't set the date formatter's time zone, it automatically sets to the system time zone as specified in Apple's docs for NSDateFormatter:
If unspecified, the system time zone is used.
Therefore the date formatter's time zone is set to be the same both implicitly for the first date and explicitly for the second date because they happen to be identical, hence you're getting the same date back.
Here is the code that work in swift4.
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!)
}
How to use :-
let localDateAsString = UTCToLocal(date: deadline!, fromFormat: "yyyy-MM-dd HH:mm:ss", toFormat: "MM-dd-yyyy hh:mm a")