Date from String in Swift but it becomes the previous day - swift

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)

Related

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

How to change time format from string in Swift 3.0

i have a string like "22:02:20" and need to format it to "10:02:00" i have try this:
let time = "22:02:00"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm:ss"
let calendar = Calendar.current
let unitFlags = Set<Calendar.Component>([.hour, .minute])
staticHoraInicio = calendar.dateComponents(unitFlags, from: dateFormatter.date(from: time))
but i get 22 and 2, how can i get 10 and 02. Also i try:
let horaF = dateFormatter.date(from: time!)
but i get something like "2000-01-02 03:00:00 +0000", ¿there is a way to format just a time string without date?
I need this to store a start time and end time coming from a DB, compare it to the current time to get if it's between, some example about how to do this???
let time = "22:02:00"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm:ss"
var fullDate = dateFormatter.date(from: time)
dateFormatter.dateFormat = "hh:mm:ss a"
var time2 = dateFormatter.string(from: fullDate!)

Incorrect time in Date from 12-Hr format Time String - Swift

I have following strings as 12-Hr format time:
let timeFrom = "05:30 AM";
let timeTo = "04:35 PM";
And trying to get date from these for comparison as follows:
let openTime = timeFrom.date(format: "hh:mm a")
let closeTime = timeTo.date(format: "hh:mm a")
With this extension :
extension String
{
func date(format:String) -> Date?
{
let formatter = DateFormatter()
formatter.dateFormat = format
formatter.timeZone = NSTimeZone.local
return formatter .date(from: self)
}
}
When I print openTime and closeTime, I'm getting incorrect values in time:
print(openTime) // 2000-01-01 00:00:00 +0000
print(closeTime) // 2000-01-01 11:00:00 +0000
Why this is so ? I think it is smoething related to time zone, so I visit NSDateFormatter return wrong date + Swift, but nothing worked for me. If anybody have the solution, please help me. Thank you !
I check with swift 3 and Xcode 8 with small changes its working please check
let timeFrom = "05:30 AM";
let timeTo = "04:35 PM";
let openTime = timeFrom.date(format: "hh:mm a")
let closeTime = timeTo.date(format: "hh:mm a")
print(openTime)
print(closeTime)
and make change in extension
extension String{
func date(format:String) -> Date?
{
let formatter = DateFormatter()
formatter.timeZone = TimeZone(abbreviation: "GMT+0:00")
formatter.dateFormat = format
//formatter.timeZone = TimeZone.current //or autoupdatingCurrent
return formatter .date(from: self)
}}

swift my current time varibale isnt showing my actual current time

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