I'm having difficulties to get the right now command with the Swift 2.0, my command lists are below:
let dateNow = NSDate()
let calendar = NSCalendar.currentCalendar()
let hour = calendar.component(NSCalendarUnit.Hour, fromDate: dateNow)
let minute = calendar.component(NSCalendarUnit.Minute, fromDate: dateNow)
The error said that instances calendar cannot be used in ViewController, and what confuses me is that the line above (the let calendar = ...) clearly defines calendar as a constant but why cannot I access it for my let hour and minute? please help
Related
I am using Swift 3 and trying to get the current hour. Below is the code i have written to get the current hour but it gives an error.
let date = Date()
let calendar = Calendar.current
let hour = calendar.component(.hour, from: date) // error
What could be the reason for this, all the sample code based on Swift 3 shows the same code snippet to get the current hour but it just don't seem to work. Please can anyone point out what could be wrong here. Thanks.
Try this code to get hour in swift 3 :
let calendar = NSCalendar.current
let hour = calendar.component(.hour, from: NSDate() as Date)
Use this code to get a current hour:
let date = Date()
let formatter = NSDateFormatter()
formatter.setFormat = "h"
print(formatter.stringFromDate(date))
Note: I did not run this code in xcode so don't just copy paste.
Consider the following code:
import UIKit
let date = Date()
guard let nycTimeZone = TimeZone(abbreviation: "EST"),
let nzTimeZone = TimeZone(abbreviation: "NZDT") else {
fatalError()
}
var nycCalendar = Calendar(identifier: .gregorian)
nycCalendar.timeZone = nycTimeZone
var nzCalendar = Calendar(identifier: .gregorian)
nzCalendar.timeZone = nzTimeZone
let now = Date()
let nycDayOfEra = nycCalendar.ordinality(of: .day, in: .era, for: now)
let nycDayOfYear = nycCalendar.ordinality(of: .day, in: .year, for: now)
var nzDayOfEra = nzCalendar.ordinality(of: .day, in: .era, for: now)
var nzDayOfYear = nzCalendar.ordinality(of: .day, in: .year, for: now)
As I write this, NYC time and Aukland NZ time give different days. That's the case I'm interested in.
With the code above, the results for nycDayOfYear and nzDayOfYear are different (as of this writing I get nycDayOfYear=42 and nzDayOfYear=43.)
That is as expected, and as desired. (I was working to answer a "how do I calculate the number of days of difference in two Dates evaluated in different time zones?" question.)
However, it would take a bunch of messy adjustments to make the above day-of-year calculation and figure out the number of days of difference between those local dates when they span year boundaries.
I therefore tried to do the calculations using ordinality(of: .day, in: .era, for: date).
However, the calculations based on calendar era give the same value regardless of the time zone of the calendar used to make do the calculation.
Why is that?
What would be a simpler way to calculate the number of calendar days difference between two dates WHEN EXPRESSED IN DIFFERENT LOCAL TIME ZONES? Like I said, my code that calculates the day of year would need additional logic added to handle dates that span calendar year boundaries.
Note that this is a different question than "How many days difference is there between 2 dates". In my question I want both dates to be expressed in different local time zones, and I'm interested in the difference in the calendar date of each of those date values.
Martin's comment about calendar calculations over long intervals giving unexpected results is as good an answer as any as to why it doesn't work.
I did come up with code that calculates the desired difference in calendar date values between 2 dates expressed in specific time zones:
let date = Date()
guard let nycTimeZone = TimeZone(abbreviation: "EST"),
let nzTimeZone = TimeZone(abbreviation: "NZDT") else {
fatalError()
}
var nycCalendar = Calendar(identifier: .gregorian)
nycCalendar.timeZone = nycTimeZone
var nzCalendar = Calendar(identifier: .gregorian)
nzCalendar.timeZone = nzTimeZone
let now = Date()
let nycDateComponents = nycCalendar.dateComponents([.month, .day, .year], from: now)
let nzDateComponents = nzCalendar.dateComponents([.month, .day, .year], from: now)
let difference = Calendar.current.dateComponents([.day],
from: nycDateComponents,
to: nzDateComponents)
let daysDifference = difference.days
First I convert the 2 dates to month/day/year DateComponents values using calendars set to their specific time zone.
Then I use the Calendar function dateComponents(_:from:to:), which lets you calculate the difference between 2 DateComponents values, in whatever units you want to use to compare them. (days, in this case)
I'm working on a project where I have labels and images that change on a daily basis. My idea on how to go about this is I add assets for the images and have multiple files where I take the text (that contains the quote).
Two questions:
Is there a better way of approaching this? (I'm fairly new to iOS, so I'm wondering if this is sound).
How can I take the current day as in: May 22? (I just want to know how to get "22").
you need to use NSDate
// Option 1
let date = NSDate() // today
let dateStringFormatter = NSDateFormatter()
dateStringFormatter.dateFormat = "dd"
let d = dateStringFormatter.stringFromDate(date)
// d = "22"
// Option 2
let d = NSCalendar.currentCalendar().component(.Day, fromDate: NSDate()) // thanks Leo-Dabus
Reference: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/
Try taking a look at this stackoverflow link on getting the current date.
How to get the current time as datetime
According to noliv in the article you should be able do :
let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute, fromDate: date)
let hour = components.hour
let minutes = components.minute
Hope this helps
I am trying to create a weekly recurring local notification using Swift. Notification is going to be set to first day of every week, and in 10:00. Ofcourse I don't want to set a notification for a past date, so I need to see if now it has passed first day of week 10:00. If not, I will create notification for today 10:00, else next week monday 10:00.
I created an extension to calculate week number for current date.
extension NSDate {
func weekOfYear() -> Int {
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(NSCalendarUnit.WeekOfYear, fromDate: self)
let weekOfYear = components.weekOfYear
return weekOfYear
}
}
I couldn't go any further than this. Any help is appreciated.
Regards.
There is an easier solution to your problem. You can use the nextDateAfterDate() method of NSCalendar:
let cal = NSCalendar.currentCalendar()
let comps = NSDateComponents()
comps.hour = 10
comps.weekday = cal.firstWeekday
let now = NSDate()
let fireDate = cal.nextDateAfterDate(now, matchingComponents: comps, options: [.MatchNextTimePreservingSmallerUnits])!
This gives the first date in the future which is at 10:00 on the first day of the week.
Hi I am trying to get the current hour and minute of the day using the following code:
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.CalendarUnitHour, fromDate: NSDate())
// Concatenate time and minutes together
let hour = components.hour
let minute = components.minute
println(components.hour)
println(components.minute)
The output for both:
components.hour output: 0
components.minute output: 9223372036854775807
It is currently 00.30 where I am. But why does components.minute print such a long number that doesn't to me seem to be the minute 30.
Also if anyone can suggest another way of getting the current time as e.g. 13:00?
Any help is much appreciated thanks!
9223372036854775807 is NSUndefinedDateComponent value. This means that NSDateComponents object doesn't have the value.
You have to join desired NSCalendarUnits with |:
let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute, fromDate: NSDate())
OR, from iOS 8, we have handy component(_:fromDate:) method to get just one component's value.
let now = NSDate()
let hour = calendar.component(.CalendarUnitHour, fromDate: now)
let minute = calendar.component(.CalendarUnitMinute, fromDate: now)