Swift Date object with different format [duplicate] - ios

This question already has answers here:
Comparing NSDates without time component
(17 answers)
Closed 5 years ago.
I've got a Date object that holds year/month/day and hour/minute/second data. I need to drop the hour/minute/second part as it's making comparing days problematic.
The issue is that the only obvious way I see of doing it is turning the day into a String and then using a DateFormatter with yyyy/mm/dd format to turn it BACK into a Date. This seems like a waste, is it really the only way?
Thanks a lot.

Never convert dates to String and back to Date.
You are looking for the startOfDay function of Calendar:
let date = Date()
let startOfDay = Calendar.current.startOfDay(for: date)

Related

Date format always return nil when using 12hr date format [duplicate]

This question already has answers here:
iOS NSDate Comparison works differently when the 24-Hour Time in date settings toggles between ON and OFF?
(2 answers)
DateFormatter doesn't return date for "HH:mm:ss"
(1 answer)
What is the best way to deal with the NSDateFormatter locale "feature"?
(4 answers)
Closed 4 years ago.
I'm trying to convert a string to a date, using the following code:
let dateFormmater = DateFormatter();
dateFormmater.timeZone = TimeZone(abbreviation: "UTC");
dateFormmater.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z";
let date = dateFormmater.date(from: "2018-06-13T15:33:47.796Z");
When the iPhone is set to 24hr mode, this works perfectly, and a new date object is created, but when the iPhone is set to 12hr mode, the date formatter returns nil.
Also, trying to get a string from date using the same date format while the iPhone is set to 24hr mode, results in a normal date, but using this in 12hr mode, results in the hours being presented both in 12hr and 24hr format,
e.g: 2018-07-05T208:17:22.019 PMZ.
note that the hour is 208 PM...
Has anyone encountered this before, and has a solution for this?
Cheers,
P.s this problem replicate able 1:1 in objective-c, using the corresponding classes.

Swift 4 days until date [duplicate]

This question already has answers here:
Getting the difference between two Dates (months/days/hours/minutes/seconds) in Swift
(20 answers)
Closed 5 years ago.
I'm struggling in calculation the days between some dates .
I want to calculate the days until new year or the minutes.
I tried a way which I saw on another post here by using dateComponents but I wasn't able to calculate.
If some one can help I would be realy happy.
Thank You !
It would be helpful to see what you've tried to give some advice, but nonetheless, you can use NSCalendar's components to accomplish this.
let calendar = Calendar.current
let startOfDay1 = calendar.startOfDay(for: date1)
let startOfDay2 = calendar.startOfDay(for: date2)
let components = calendar.dateComponents([.day], from: startOfDay1, to: startOfDay2)
You can customize that above to get more specific minutes from your date object.
https://developer.apple.com/documentation/foundation/nscalendar/1407925-components
Edit: For Swift 4, you don't need to bridge. You can use Calendar directly (edited code above). https://developer.apple.com/documentation/foundation/calendar/2293176-datecomponents

How to convert sql timestamp to date in swift? [duplicate]

This question already has answers here:
Convert milliseconds to NSDate
(3 answers)
Closed 6 years ago.
I get timestamp results from database SQL query like 1465536311 or 1465540078. How to convert such number to current date and time in swift?
From NSDate Class Reference :
let date = NSDate(timeIntervalSince1970: 1465536311)

How do I get a label in Xcode to show the day of the week (Swift/Swift 2) [duplicate]

This question already has answers here:
Displaying the Day Of The Week From Date Picker
(2 answers)
Closed 7 years ago.
I'm an absolutely coding newb and I want to create a school planner app. I have the general nuts and bolts sorted - but I want to create a function where a label displays the day of the week, which a button would then interpret and would then send the user to the appropriate View Controller with that day's timetable in.
I've tried YouTube and of course here, and I can make no sense of it at all. Can someone treat me like a little baby and explain it to me. The name of the label is DayLabel1 and I think I can connect it as an IBOutlet.
I make no sense out of this whatsoever, and if you can't help me, I am either
a) doomed
b) still doomed
This is not a duplicate as I'm not wanting a date picker. I'm a newb and just want a hand.
Thank you! :-)
[[[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:[NSDate date]] weekday];
This code gives you to number of day in week which start from Sunday (index of Sunday is 0). You can make an String enum to get string using this index.
Here is the Swift:
let calendar = NSCalendar.currentCalendar()
let date = NSDate()
let dateComponent = calendar.components(NSCalendarUnit.CalendarUnitWeekday, fromDate: date)
let weekday = dateComponent.weekday

Getting a NSDate object from a string

Before flagging this question as a duplicate, please read on.
I need to compare two NSDates. A date I get from a server with the current date.
From NSDate.date() I get this date 2014-09-25 12:48:23 +0000 which is wrong (the time part). I needed to add 5 hours to get the current time so I did the following.
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd hh:mm:ss ZZZZZ"
let dateString = formatter.stringFromDate(NSDate.date())
The result is the correct date - 2014-09-25 06:21:56 +05:30
But there's a little hitch. This date is a String, not a NSDate. I need it to be a NSDate object to compare it with another date.
I tried converting it back like this,
let date = formatter.dateFromString(dateString)
And I get a wrong result - 2014-09-25 00:55:53 +0000. I tried passing the date string to a new NSDateFormatter to see if that works but again I still I get the wrong date.
My question is, how can I convert this date string to a NSDate object which also retains the correct time.
Thank you.
You are thoroughly confused about NSDate.
An NSDate is a point in time. It has no time zone information. If we both call [NSDate date] right now, we will get the same NSDate, even when you are in India and I'm in the UK. That's intentional. It's the same time. The time displayed on my watch and on your watch is different, but NSDate is the same. You can't convert NSDate to an "Indian" date.
You use calendars and timezones to convert NSDates to strings that you display to a user, in the way your users expect it. That's what you have done. You got a string that makes sense to Indian users. If an Indian user types a time, you take that string and convert it to an NSDate. The NSDate will be in Universal time. If you and I both typed in the time on our watch right now and converted it, you would type a time that looks like 5 1/2 hours earlier than mine. But it's the same time. If you convert it to NSDate, we will both get the exact same NSDate.
So how do you change your NSDate? Quite simple: You don't. NSDate is absolute time, independent of your location on earth.
Upon further Googling, I came across this post. The method described in it does exactly what I want. The original code is in Objective-C and since my question is in Swift, I'm going to post its Swift translation. \
func toLocalTime() -> NSDate {
let timeZone = NSTimeZone.localTimeZone()
let seconds = timeZone.secondsFromGMTForDate(self)
return NSDate(timeInterval: Double(seconds), sinceDate: self)
}
I added these as extension methods of NSDate so you can simply call them like this.
NSDate.date().toLocalTime()
You can compare two dates using any of the following NSDate functions: compare, earlierDate, laterDate, isEqualToDate. You should not compare date strings (oh, goodness, no, think of the nightmare); convert 'date strings' into 'NSDate' as soon as inputed.
In order to compare two dates that arose from strings correctly, you'll need the date strings to be unambiguous. In practice, that requires the date to have a time zone attached. If your server isn't providing a time zone and can't be modified to provide one, then you'll be forced to assume one (which would typically be the time zone where the server is located, assuming one server).

Resources