Get Current Date in Swift 3

Get current date in Swift 3?

You say in a comment you want to get "15.09.2016".

For this, use Date and DateFormatter:

let date = Date()
let formatter = DateFormatter()

Give the format you want to the formatter:

formatter.dateFormat = "dd.MM.yyyy"

Get the result string:

let result = formatter.string(from: date)

Set your label:

label.text = result

Result:

15.09.2016

How to get the current time as datetime

Update for Swift 3:

let date = Date()
let calendar = Calendar.current
let hour = calendar.component(.hour, from: date)
let minutes = calendar.component(.minute, from: date)

I do this:

let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute, fromDate: date)
let hour = components.hour
let minutes = components.minute

See the same question in objective-c How do I get hour and minutes from NSDate?

Compared to Nate’s answer, you’ll get numbers with this one, not strings… pick your choice!

How to get current date in swift 3?

For getting abbreviation from NSTimeZone.

static var localTimeZoneAbbreviation: String { return  NSTimeZone.local.abbreviation(for: Date())! }

For getting current Date.

let currentDate = Date()

How to get Date from String in swift 3?

Military time (24-value hours) uses the capital 'H'. Try this for your formatting String:

dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZ"

How to get start date and end date of the current month (Swift 3)

You should write this simple code:

let dateFormatter = DateFormatter()
let date = Date()
dateFormatter.dateFormat = "dd-MM-yyyy"

For start Date:

let comp: DateComponents = Calendar.current.dateComponents([.year, .month], from: date)
let startOfMonth = Calendar.current.date(from: comp)!
print(dateFormatter.string(from: startOfMonth))

For end Date:

var comps2 = DateComponents()
comps2.month = 1
comps2.day = -1
let endOfMonth = Calendar.current.date(byAdding: comps2, to: startOfMonth)
print(dateFormatter.string(from: endOfMonth!))

swift 3 set date picker current date and calculate difference

to set current date -

yourDatePicker.setDate(Date(), false)

to get the difference in days -

Calendar.current.dateComponents([.day], from: yourDatePicker.date, to: self).day


Related Topics



Leave a reply



Submit