How to Separate The Date and Time Components of Nsdate() in Swift

How to separate the date and time components of NSDate() in Swift?

You need to use Calendar to break a date apart, using CalendarUnit to specify what components you want.

let calendar = Calendar.current
let components = calendar.dateComponents([.month, .day, .year, .hour, .minute], from: Date())
print("Hour: \(components.hour)")
print("Minute: \(components.minute)")
print("Day: \(components.day)")
print("Month: \(components.month)")
print("Year: \(components.year)")

How can i divide NSDate() into pieces?

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)

NSDate with date component from one and time component from another NSDate

Assume date1 and date2 are your two NSDate values. date1 contains your date components and date2 contains your time components. Here's how you would combine them together:

NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

// Extract date components into components1
NSDateComponents *components1 = [gregorianCalendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit
fromDate:date1];

// Extract time components into components2
NSDateComponents *components2 = [gregorianCalendar components:NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit
fromDate:date2];

// Combine date and time into components3
NSDateComponents *components3 = [[NSDateComponents alloc] init];

[components3 setYear:components1.year];
[components3 setMonth:components1.month];
[components3 setDay:components1.day];

[components3 setHour:components2.hour];
[components3 setMinute:components2.minute];
[components3 setSecond:components2.second];

// Generate a new NSDate from components3.
NSDate *combinedDate = [gregorianCalendar dateFromComponents:components3];

// combinedDate contains both your date and time!

For iOS 8.0 +

NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

// Extract date components into components1
NSDateComponents *components1 = [gregorianCalendar components:(NSCalendarUnit)(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay)
fromDate:date1];

// Extract time components into components2
NSDateComponents *components2 = [gregorianCalendar components:(NSCalendarUnit)(NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond)
fromDate:date2];

// Combine date and time into components3
NSDateComponents *components3 = [[NSDateComponents alloc] init];

[components3 setYear:components1.year];
[components3 setMonth:components1.month];
[components3 setDay:components1.day];

[components3 setHour:components2.hour];
[components3 setMinute:components2.minute];
[components3 setSecond:components2.second];

// Generate a new NSDate from components3.
NSDate * combinedDate = [gregorianCalendar dateFromComponents:components3];

// combinedDate contains both your date and time!

Extract date components from a NSDate ignoring local time and time zones

You have to set the timezone on the calendar.

let date = NSDate()
print(date) // Prints 2016-10-20 20:10:20 +0000 (Good Universal Time)
var calendar = Calendar.current
calendar.timeZone = TimeZone(abbreviation: "UTC")!
let hour = calendar.component(.hour, from: date as Date)
print(hour) // Prints 20

Truncate time from NSDate SWIFT

Here is the code to print the current date in your desired format:

let today = NSDate().dateByAddingTimeInterval(0)     

let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = .MediumStyle

let dateToPrint: NSString = dateFormatter.stringFromDate(today) as NSString

println(dateToPrint.uppercaseString)

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

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.

How can I set an NSDate object to midnight?

Your statement

The problem with the above method is that you can only set one unit of
time ...

is not correct. NSCalendarUnit conforms to the RawOptionSetType protocol which
inherits from BitwiseOperationsType. This means that the options can be bitwise
combined with & and |.

In Swift 2 (Xcode 7) this was changed again to be
an OptionSetType which offers a set-like interface, see
for example Error combining NSCalendarUnit with OR (pipe) in Swift 2.0.

Therefore the following compiles and works in iOS 7 and iOS 8:

let date = NSDate()
let cal = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!

// Swift 1.2:
let components = cal.components(.CalendarUnitDay | .CalendarUnitMonth | .CalendarUnitYear, fromDate: date)
// Swift 2:
let components = cal.components([.Day , .Month, .Year ], fromDate: date)

let newDate = cal.dateFromComponents(components)

(Note that I have omitted the type annotations for the variables, the Swift compiler
infers the type automatically from the expression on the right hand side of
the assignments.)

Determining the start of the given day (midnight) can also done
with the rangeOfUnit() method (iOS 7 and iOS 8):

let date = NSDate()
let cal = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
var newDate : NSDate?

// Swift 1.2:
cal.rangeOfUnit(.CalendarUnitDay, startDate: &newDate, interval: nil, forDate: date)
// Swift 2:
cal.rangeOfUnit(.Day, startDate: &newDate, interval: nil, forDate: date)

If your deployment target is iOS 8 then it is even simpler:

let date = NSDate()
let cal = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
let newDate = cal.startOfDayForDate(date)

Update for Swift 3 (Xcode 8):

let date = Date()
let cal = Calendar(identifier: .gregorian)
let newDate = cal.startOfDay(for: date)

How can I extract number of years, months, and days since a date in Swift

Like you said, you will need UILabel's for each of the date components. You can then extract the components using custom date formatting strings instead of using NSDateFormatterStye.ShortStyle. This gives you the most flexibility. The formatting strings follow a unicode standard.

I can't test the code in the context of your project, but if you add the labels and connect them correctly to Xcode, I believe that this code will do exactly what you want:

class DatePickerController: UIViewController {

@IBOutlet var datePicker:UIDatePicker!
@IBOutlet var dayDisplay: UILabel!
@IBOutlet var monthDisplay: UILabel!
@IBOutlet var yearDisplay: UILabel!

override func viewDidLoad() {
super.viewDidLoad()

// Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

@IBAction func datePickerChanged(sender: AnyObject) {
setDate()
}

let dateFormatter = NSDateFormatter()

// MARK: - Date Format
func setDate() {
dateFormatter.dateFormat = "dd"
dayDisplay.text = dateFormatter.stringFromDate(datePicker.date)
dateFormatter.dateFormat = "MM"
monthDisplay.text = dateFormatter.stringFromDate(datePicker.date)
dateFormatter.dateFormat = "yyyy"
yearDisplay.text = dateFormatter.stringFromDate(datePicker.date)
}

}


Related Topics



Leave a reply



Submit