How to get local time zone date in swift 3 - ios

I am getting year,month and day from a given date in this way.
let today=Date()
var calendar = Calendar.current
calendar.timeZone = .current
let components = calendar.dateComponents([.year, .month, .day], from: today)
let day=components.day
But I'm getting one day ahead from my current day. How can I solve this?

let date = Date().description(with: Locale.current)
print("date ---> \(date)")
Result: date ---> Tuesday, June 20, 2017 at 4:35:15 PM India Standard Time
I'm getting perfect system/local time.
You code is working,
let today=Date()
var calendar = Calendar.current
calendar.timeZone = .current
let components = calendar.dateComponents([.year, .month, .day, .hour, .minute], from: today)
let day = components.day
let hour = components.hour
let minute = components.minute
print("day = \(day)\nhour = \(hour)\nminute = \(minute)")
Result: day = Optional(20) hour = Optional(16) minute = Optional(35)

Get Local Date and Time
Swift 5:
let today = Date()
let timeZone = Double(TimeZone.current.secondsFromGMT(for: today))
let localDate = Calendar.current.date(byAdding: .second, value: Int(timeZone), to: today) ?? Date()

As per the documentation:
If you want “date information in a given time zone” in order to
display it, you should use DateFormatter to format the date.
eg:
// If date is "Dec 7, 2018 at 6:34 AM" UTC
let today=Date() // is always UTC
var calendar = Calendar.current
calendar.timeZone = .current
let components = calendar.dateComponents([.year, .month, .day], from: today)
let day = components.day // Is 7
// To print with local version
let myFormatter = DateFormatter()
myFormatter.timeZone = TimeZone(secondsFromGMT: 3600*10)
myFormatter.dateFormat = "dd"
print(myFormatter.string(from: today)) // prints "07\n"
myFormatter.timeZone = TimeZone(secondsFromGMT: -3600*11)
print(myFormatter.string(from: today)) // prints "06\n"

Related

Swift date format with millisecond component

All,
I have a date format "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" and I need to set the millisecond value, but date component does not provide millisecond attribute.
Below is my code for setting custom values in hour, minute, second. I also need to set millisecond to 0/999 value.
static func getToadyStartInUTC() -> String{
let todaydate = Date()
let formatter = DateFormatter()
var components = Calendar.current.dateComponents([.year, .month, .day, .hour], from: todaydate)
components.hour = 0
components.minute = 0
components.second = 0
let calendar = Calendar.current
let startDate = calendar.date(from: components)!
print("\(startDate)")
formatter.timeZone = TimeZone(identifier: "UTC")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
return formatter.string(from: startDate)
}
How can I set the millisecond value in date component?
An alternative solution with Calendar API to get startDate and ISO8601DateFormatter
static func getToadyStartInUTC() -> String {
let todaydate = Date()
var calendar = Calendar.current
let timeZone = TimeZone(secondsFromGMT: 0)!
calendar.timeZone = timeZone
let startDate = calendar.startOfDay(for: todaydate)
var components = calendar.dateComponents(in: timeZone, from: startDate)
components.nanosecond = 999000000
let formatter = ISO8601DateFormatter()
formatter.formatOptions.insert(.withFractionalSeconds)
return formatter.string(from: components.date!)
}
let todaydate = Date()
var calendar = Calendar.current
calendar.timeZone = TimeZone(identifier: "UTC")
let startDate = calendar.startOfDay(for: todaydate)
var components = calendar.dateComponents(in: timeZone, from: startDate)
components.nanosecond = 999000000
let formatter = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
formatter.string(from: components.date!)

issues in comparing Day from Date in swift 4

Comparison is required to check date is past date day.
I have tried with this
let calendar = NSCalendar.current
//Get just MM/dd/yyyy from current date
let components = calendar.dateComponents([], from: Date())
//Convert to NSDate
let pastDates = self.calendar.selectedDates.filter { $0 < calendar.date(from: components as DateComponents)! }
Update the below line to give you a date object,
let components = calendar.dateComponents([.month, .day, .year], from: Date())
Currently you are not providing any date component in the array so you will not get a date object.
I didn't understood what is your question properly, but hope this helps you:
let beforeDateStr = "04/12/2018"
let todayDate = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd/yyyy"
let beforeDateFormatted = dateFormatter.date(from: beforeDateStr)
if Calendar.current.compare(todayDate, to: beforeDateFormatted!, toGranularity: .day) == .orderedDescending {
print("before date day is lesser than current date")
} else {
print("before date day is equal or greater than todays date")
}
To find the date is smaller or bigger:
You can use this simple Code:
let differenceBetweenTwoDate = Calendar.current.dateComponents([.day], from: previousDate, to: Date())
if differenceBetweenTwoDate.day! > 0{
print("date is bigger")
}else{
print("date is smaller")
}
Hope it Helps!
This is how you can add hours or days in current date and time -
calendar.date(byAdding: .hour, value: 1, to: currentDate)
calendar.date(byAdding: .day, value: 7, to: currentDate)
And this is how you can compare 2 dates and calculate hours, mins and also days
let calendar = Calendar.current
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
let anyDataTime = dateFormatter.date(from: anotherDateTime)
let components = calendar.dateComponents([.minute], from: Date(), to: anyDataTime!)
let hour = (Double(components.minute!) / 60.0).rounded()

Swift - Get date from day of year

We can get day of year for date using below line.
let day = cal.ordinalityOfUnit(.Day, inUnit: .Year, forDate: date)
But how can we get the date from day of year?
If you know the year you can get DateComponents date property as follow:
extension Calendar {
static let iso8601 = Calendar(identifier: .iso8601)
}
let now = Date()
let day = Calendar.iso8601.ordinality(of: .day, in: .year, for: now)! // 121
let year = Calendar.iso8601.component(.year, from: now) // 2017
let date = DateComponents(calendar: .iso8601, year: year, day: day).date // "May 1, 2017, 12:00 AM"
or using DateFormatter
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy D"
if let date = dateFormatter.date(from: "\(year) \(day)") {
dateFormatter.dateStyle = .medium
dateFormatter.timeStyle = .short
dateFormatter.string(from: date) // "May 1, 2017, 12:00 AM"
}
You cannot go the other way. Going from a date to a day of the year discards all other information, you are left with only the day of the year (you no longer know what year). To go back to a full date you would have to make assumptions about the year the day was in.
The answer that #LeoDabus gave is more succinct than this, so it is perhaps the better choice. Having said that, this is the code that I would have used:
let dateComponents = NSDateComponents();
dateComponents.year = 2015
dateComponents.day = day
let calendar = NSCalendar.currentCalendar()
let date = calendar.dateFromComponents(dateComponents)
Updated for Swift 4:
let dateComponents = NSDateComponents();
dateComponents.year = 2018
dateComponents.day = someDay
let calendar = NSCalendar.current
let date = calendar.date(from: dateComponents as DateComponents)

Swift Datepicker with minimum date

Goord Morning all together,
i have an app with ios 8 and swift.
in there is a UIViewcontroller within a UIDatepicker
I set a minimum date. for example the date of today: 2 | May | 2015
with this solution it should not be possible to set a date which is in the past
but if would like to set this date 15 | January | 2016
i set at first the day to 15
than the month to january but then the UIDatepicker goes back to the minimum date 2 May 2015
is it be possible, that wenn change the day to 15 and the month to january, that the year changes automaticly to 2016?
Let your minimumDate unset and try to configure it by code...
Try this:
#IBAction func changeValue(sender: UIDatePicker)
{
//Get time Now, and convert to a NSCalendar
//Specify the minimun date if you want.
let now = NSDate()
let nowCalendar = NSCalendar.currentCalendar()
let nowComponents = nowCalendar.components([.Day, .Month, .Year], fromDate: now)
//Compare if date is lesser than now and then create a new date
if nowCalendar.compareDate(sender.date, toDate: now, toUnitGranularity: [.Day, .Month, .Year]) == NSComparisonResult.OrderedAscending
{
let dateCalendar = NSCalendar.currentCalendar()
let dateComponents = dateCalendar.components([.Day, .Month, .Year], fromDate: sender.date)
dateComponents.year = nowComponents.year + 1
let newDate = dateCalendar.dateFromComponents(dateComponents)
sender.date = newDate!
}
}
///Swift4 Version - I think it may works with 3 too.
#IBAction func changeValue(sender: UIDatePicker)
{
//Get time Now, and convert to a NSCalendar
//Specify the minimun date if you want.
let now = Date()
let nowCalendar = Calendar.current
let nowComponents = nowCalendar.dateComponents([.day, .month, .year], from: now)
//Compare if date is lesser than now and then create a new date
if nowCalendar.compare(sender.date, to: now, toGranularity: Calendar.Component.day) == ComparisonResult.orderedAscending
{
var dateCalendar = Calendar.current
var dateComponents = dateCalendar.dateComponents([.day, .month, .year], from: sender.date)
guard let year = nowComponents.year else { return }
dateComponents.year = year + 1
let newDate = dateCalendar.date(from:dateComponents)
sender.date = newDate!
}
}
I published a complete example working in playground if you wish to play a little.
https://gist.github.com/dedeexe/4878f78d7e1d5fe8b372ef84de629b59
For swift 4:
I have like this.
1. My function:
func AddDaysToToday(days: Int) -> Date? {
var dateComponents = DateComponents()
dateComponents.day = days
return Func.GetCalendar(tz: .utc).date(byAdding: dateComponents, to: Date()) //you can return your own Date here.
}
In my VC:
let today = DateFunc.AddDaysToToday(days: 0)
datePicker.minimumDate = today

How to get the hour of the day with Swift?

How would I get the hour of the day in Swift.
I have tried NSCalendar and NSDateComponents, but I'm afraid I'm just starting with Swift.
Swift 5.0 / 4.0 / 3.0
let hour = Calendar.current.component(.hour, from: Date())
Or, if you're interested in 12 hour AM/PM date format, then use NSDateFormatter
let formatter = DateFormatter()
formatter.dateFormat = "hh a" // "a" prints "pm" or "am"
let hourString = formatter.string(from: Date()) // "12 AM"
If you want minutes, seconds and others, do as following
let date = Date() // save date, so all components use the same date
let calendar = Calendar.current // or e.g. Calendar(identifier: .persian)
let hour = calendar.component(.hour, from: date)
let minute = calendar.component(.minute, from: date)
let second = calendar.component(.second, from: date)
Check out available components on Apple docs:
.era, .year, .month, .day, .hour, .minute, .second,
.weekday, .weekdayOrdinal, .quarter, weekOfMonth, .weekOfYear,
.yearForWeekOfYear, .nanosecond, .calendar, .timezone
Swift 2.0
let hour = NSCalendar.currentCalendar().component(.Hour, fromDate: NSDate())
Swift 1.0
let hour = NSCalendar.currentCalendar().component(.CalendarUnitHour, fromDate: NSDate())
Swift 3:
let date = Date()// Aug 25, 2017, 11:55 AM
let calendar = Calendar.current
let hour = calendar.component(.hour, from: date) //11
let minute = calendar.component(.minute, from: date) //55
let sec = calendar.component(.second, from: date) //33
let weekDay = calendar.component(.weekday, from: date) //6 (Friday)
Get any of component available from the API below
public enum Component {
case era
case year
case month
case day
case hour
case minute
case second
case weekday
case weekdayOrdinal
case quarter
case weekOfMonth
case weekOfYear
case yearForWeekOfYear
case nanosecond
case calendar
case timeZone
}
Swift 2:
let currentHour = NSCalendar.currentCalendar().component(.Hour, fromDate: NSDate())
This could be enough :
let currentDate = NSDate() // You can input the custom as well
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute, fromDate: currentDate)
let currentHour = components.hour // You can play around with the ""components""
If you want the current hour in a String, this is as short and readable I could think of.
let formatter = NSDateFormatter()
formatter.dateFormat = "HH"
let timeString = formatter.stringFromDate(NSDate())
Finally I was able to find the easiest solution after struggling for a time
let dateComponents = NSCalendar.currentCalendar().components(NSCalendarUnit.HourCalendarUnit, fromDate: NSDate())
let nHourOfDay = dateComponents.hour
For Swift 2.0:
let hour = NSCalendar.currentCalendar().component(NSCalendarUnit.Hour, fromDate: NSDate())
Here is a reference example for how I do it (DateUtils.swift) -
Example Use:
let today = DateUtils.getToday();
let hr = DateUtils.getHours(today);
let min = DateUtils.getMinutes(today);
... (etc.) ...
DateUtils.swift:
//Field wrapper routines
class func getToday() -> Date { return Date(); }
class func getHours(_ date : Date) -> Int { return Calendar.current.component(.hour, from: date); }
class func getMinutes(_ date : Date) -> Int { return Calendar.current.component(.minute, from: date); }
... (continued for all fields, see file) ...
You can get the integer value of the current hour in one step like this:
let currentHour = NSCalendar.currentCalendar().components(.Hour, fromDate: NSDate()).hour

Resources