How to fetch day, month and hour from NSDate in Swift - swift

I have an NSDate object called reservationDate and I want to fetch day, month and hour from the Date. However, I'm getting wrong values. How can I get these values?
The value of the reservationDate object
reservationDate NSDate 2016-08-05 21:00:00 UTC
thus I expect to get 5 as a day and 21 as a hour however I'm receiving 6 as a day and 0 as a hour. Should I expect something else?
let unitFlags: NSCalendarUnit = [.Hour, .Day, .Month, .Year]
let components = NSCalendar.currentCalendar().components(unitFlags, fromDate: reservationDate)
let day = components.day
let hour = components.hour

You have not set Time zone. Please assign it "UTC".
NSCalendar.currentCalendar().timeZone = NSTimeZone(name: "UTC")!

Try to set timezone with Calendar object with UTC
let unitFlags: NSCalendarUnit = [.Hour, .Day, .Month, .Year]
let calendar = NSCalendar.currentCalendar()
calendar.timeZone = NSTimeZone(name: "UTC")!
let components = calendar.components(unitFlags, fromDate: NSDate())
let day = components.day
let hour = components.hour

let currentDate = NSDate()
let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = NSDateFormatterStyle.FullStyle
var convertedDate = dateFormatter.stringFromDate(currentDate)
dateFormatter.dateFormat = "EEEE, MMMM dd, yyyy, HH:mm"
convertedDate = dateFormatter.stringFromDate(currentDate)

Related

Format hour and minute integers as the String "9:30 am"

How can I express hour and minute integer values as a String formatted like "9:30 am"?
Currently, I have:
let hour: Int = 9
let minute: Int = 30
var dateComponents = DateComponents()
dateComponents.hour = hour
dateComponents.minute = minute
let time: String = DateComponentsFormatter.localizedString(from: dateComponents, unitsStyle: DateComponentsFormatter.UnitsStyle.positional)
print(time) // Prints "9:30", not "9:30 am"
I know I can manually concatenate the time meridian at the end, but I'm hoping there's a built in function for this. Perhaps a different UnitsStyle?
You could use DateFormatter to achieve this.
let formatter = DateFormatter()
formatter.dateFormat = "hh:mm a"
formatter.amSymbol = "am"
formatter.pmSymbol = "pm"
let dateString = formatter.string(from: Date())
print(dateString) // prints "12:17 pm"
If you want to only include single digits for the hour, then you only include one "h" in the dateFormat:
formatter.dateFormat = "h:mm a" // prints "1:30 pm" instead of "01:30 pm"
let formatter = DateFormatter()
formatter.dateFormat = "hh:mm a"
formatter.calendar = .current
let hour: Int = 9
let minute: Int = 30
var dateComponents = DateComponents()
dateComponents.hour = hour
dateComponents.minute = minute
If let fixedDate: Date = Calendar.current.date(from: dateComponents) {
let formattedString = formatter.string(from: fixedDate)
print(formattedString) //prints 09:30 AM
}
You need to add current calendar/date to get am or pm from your time from what I know.
EDIT:
Thanks to Leo Dabus in the comments for pointing this out: the above method will result in a date that is on January 1st 0001, if the date is important for you you have to specify the date (day/month/year)
for example:
let date = Date()
let formatter = DateFormatter()
formatter.dateFormat = "hh:mm a"
formatter.calendar = .current
let hour: Int = 9
let minute: Int = 30
var dateComponents = DateComponents()
dateComponents.hour = hour
dateComponents.minute = minute
dateComponents.year = Calendar.current.component(.year, from: date)
dateComponents.month = Calendar.current.component(.month, from: date)
dateComponents.day = Calendar.current.component(.day, from: date)
If let fixedDate: Date = Calendar.current.date(from: dateComponents) {
let formattedString = formatter.string(from: fixedDate)
print(formattedString)
}

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 get UTC for date in midnigs in swift

Can somebody help me to get current UTC date time.
I am trying:
let cal = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
let components = cal.components([.Day , .Month, .Year ], fromDate: NSDate())
let refDate = cal.dateFromComponents(components)
But I am getting 1/12/2017 23:00:00
This is seems UTC local time.
I want to get UTC for current date at midnight.
In database I save date as number of seconds but on server it is saved as 1/13/2017 00:00:00 and in swift I am getting 1/12/2017 23:00:00 so I can't get values as they are different I don't understand what I need to do to get same UTC.
In database I save date as long number of seconds in swift I am getting it by UInt64(floor(refDate!.timeIntervalSince1970)) but date is incorrect.
You need to set hour, minute and second property of NSDateComponents to 0
let cal = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
cal.timeZone = NSTimeZone(name: "UTC")!
let components = cal.components([.Day , .Month, .Year,.Hour, .Minute, .Second], fromDate: NSDate())
components.hour = 0
components.minute = 0
components.second = 0
let refDate = cal.dateFromComponents(components)
Or from iOS 8 you can also use startOfDayForDate
let cal = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
cal.timeZone = NSTimeZone(name: "UTC")!
let refDate = cal.startOfDayForDate(NSDate())
print(refDate)

How can i divide NSDate() into pieces?

func date() -> String {
return NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: NSDateFormatterStyle.ShortStyle, timeStyle: NSDateFormatterStyle.MediumStyle)
}
var date = date() // 2016. 5. 13. 오전 4:45:16
above code, date obtain korean current value of date every time that i call date()
I'll hope to have refresh new value from NSDate(), and so insert refresh new value into varibles like below code
var yearMonDay = "2016. 5. 13"
var hourMinSec = "오전 4:45:16"
hmmm Are there methods to divide NSDate() into pieces like below code?
yearMonDay = NSDate().?? // refresh date "year: month: day"
hourMinSec = NSDate().?? // refresh date "am/fm hour:minute:second
Splitting up components like hour can be done using the components of the NSCalendar
let today = NSDate()
let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)!
let components = calendar.components([.Year, .Month, .Day, .Hour, .Minute, .Second], fromDate: today)
print("\(components.month) \(components.day) \(components.year)")
print("\(components.hour) \(components.minute) \(components.second)")
With the NSDate formatter you can find the names
let formatter = NSDateFormatter()
let monthName = formatter.monthSymbols[components.month-1]
print(monthName)
You can use the NSDateFormatterStyle:
// get the current date and time
let currentDateTime = NSDate()
// initialize the date formatter and set the style
let formatter = NSDateFormatter()
// October 26, 2015
formatter.timeStyle = NSDateFormatterStyle.NoStyle
formatter.dateStyle = NSDateFormatterStyle.LongStyle
formatter.stringFromDate(currentDateTime)
// 6:00:50 PM
formatter.timeStyle = NSDateFormatterStyle.MediumStyle
formatter.dateStyle = NSDateFormatterStyle.NoStyle
formatter.stringFromDate(currentDateTime)

How to change the current day's hours and minutes in Swift?

If I create a Date() to get the current date and time, I want to create a new date from that but with different hour, minute, and zero seconds, what's the easiest way to do it using Swift? I've been finding so many examples with 'getting' but not 'setting'.
Be aware that for locales that uses Daylight Saving Times, on clock change days, some hours may not exist or they may occur twice. Both solutions below return a Date? and use force-unwrapping. You should handle possible nil in your app.
Swift 3+ and iOS 8 / OS X 10.9 or later
let date = Calendar.current.date(bySettingHour: 9, minute: 30, second: 0, of: Date())!
Swift 2
Use NSDateComponents / DateComponents:
let gregorian = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
let now = NSDate()
let components = gregorian.components([.Year, .Month, .Day, .Hour, .Minute, .Second], fromDate: now)
// Change the time to 9:30:00 in your locale
components.hour = 9
components.minute = 30
components.second = 0
let date = gregorian.dateFromComponents(components)!
Note that if you call print(date), the printed time is in UTC. It's the same moment in time, just expressed in a different timezone from yours. Use a NSDateFormatter to convert it to your local time.
swift 3 date extension with timezone
extension Date {
public func setTime(hour: Int, min: Int, sec: Int, timeZoneAbbrev: String = "UTC") -> Date? {
let x: Set<Calendar.Component> = [.year, .month, .day, .hour, .minute, .second]
let cal = Calendar.current
var components = cal.dateComponents(x, from: self)
components.timeZone = TimeZone(abbreviation: timeZoneAbbrev)
components.hour = hour
components.minute = min
components.second = sec
return cal.date(from: components)
}
}
//Increase the day & hours in Swift
let dateformat = DateFormatter()
let timeformat = DateFormatter()
dateformat.dateStyle = .medium
timeformat.timeStyle = .medium
//Increase Day
let currentdate = Date()
let currentdateshow = dateformat.string(from: currentdate)
textfield2.text = currentdateshow
let myCurrentdate = dateformat.date(from: dateTimeString)!
let tomorrow = Calendar.current.date(byAdding: .day, value: 1, to: myCurrentdate) // Increase 1 Day
let tomorrowday = dateformat.string(from: tomorrow!)
text3.text = tomorrowday
text3.isEnabled = false
//increase Time
let time = Date()
let currenttime = timeformat.string(from: time)
text4.text = currenttime
let mycurrenttime = timeformat.date(from: currenttime)!
let increasetime = Calendar.current.date(byAdding: .hour, value: 2, to: mycurrenttime) //increase 2 hrs.
let increasemytime = timeformat.string(from: increasetime!)
text5.text = increasemytime