How can i divide NSDate() into pieces? - swift

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)

Related

Set Tomorrow Date from custom date swift

i have an app and user can select date from that. How to Set Tomorrow Date from selected date. For example if user select date 24 it print 25 and if user select date 31 it print 1.
Right now i'm using current date to set tomorrow's date
let dates = Date()
var tomorrow: Date {
return Calendar.current.date(byAdding: .day, value: 1, to: Date())!
}
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd"
let dateOutDefault = dateFormatter.string(from: tomorrow as Date)
How to do something like that using custom date?
import Foundation
extension Date {
var tomorrow: Date? {
return Calendar.current.date(byAdding: .day, value: 1, to: self)
}
}
let today = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM dd, yyyy, HH:mm b"
if let tomorrow = today.tomorrow {
let tomorrowString = dateFormatter.string(from: tomorrow)
print("\(tomorrowString)" // "Mar 23, 2017, 00:14 AM\n"
}
let dayComponenet = NSDateComponents()
dayComponenet.day = 1
let theCalendar = NSCalendar.currentCalendar()
let nextDate = theCalendar.dateByAddingComponents(dayComponenet, toDate: NSDate(), options: NSCalendarOptions(rawValue: UInt(0)))
print(nextDate);
let date = nextDate
let unitFlags: NSCalendarUnit = [.Hour, .Day, .Month, .Year]
let components = NSCalendar.currentCalendar().components(unitFlags, fromDate: date!)
print(components.day);

Show Date with DateFormatter

I'm looking for a way to display the current date in a label with Swift 3.
Currently I'm using DateFormatter.dateFormat but the only output I get is
dd.MM.yyyy
Here is the line of code:
lbl_Date.text = DateFormatter.dateFormat(fromTemplate: "MMddyyyy", options: 0, locale: NSLocale(localeIdentifier: "de-AT") as Locale)
And my expected output for today should be:
11.12.2016
I know that I can get the time with the dateTimeComponents but I haven't figured out how I can get only the date (day, month and year) in my label:
// get the current date and time
let currentDateTime = Date()
// get the user's calendar
let userCalendar = Calendar.current
// choose which date and time components are needed
let requestedComponents: Set<Calendar.Component> = [
.year,
.month,
.day,
.hour,
.minute,
.second
]
// get the components
let dateTimeComponents = userCalendar.dateComponents(requestedComponents, from: currentDateTime)
What is there the cleanest way to display the current date in my label?
Forget Calendar and DateComponents. Use DateFormatter
let currentDateTime = Date()
let formatter = DateFormatter()
If you want a fixed format set the dateFormat to
formatter.dateFormat = "dd.MM.yyyy"
alternatively if you want a format depending on the current locale set timeStyle and dateStyle rather than the format property
formatter.timeStyle = .none
formatter.dateStyle = .medium
Now get the string
let dateString = formatter.string(from: currentDateTime)

Unable to get current date in Swift 3.0

I am using below code to get current date and formatting it.
But seeing error "Cannot invoke initiliazer for type "Date" with no arguments"
let currentDateTime = Date()
// initialize the date formatter and set the style
let formatter = DateFormatter()
formatter.timeStyle = .medium
formatter.dateStyle = .long
// get the date time String from the date object
formatter.string(from: currentDateTime) // October 8, 2016 at 10:48:53 PM
screenshot
You may not be placing the code in the correct location. Make sure it is inside a function of some kind. You can could even place this inside viewDidLoad().
override func viewDidLoad() {
super.viewDidLoad()
let currentDateTime = Date()
// initialize the date formatter and set the style
let formatter = DateFormatter()
formatter.timeStyle = .medium
formatter.dateStyle = .long
// get the date time String from the date object
let mytime = formatter.string(from: currentDateTime) // October 8, 2016 at 10:48:53 PM
print(mytime)
}
func getcurrentDate() {
let currentDateTime = Date()
// initialize the date formatter and set the style
let formatter = DateFormatter()
formatter.timeStyle = .medium
formatter.dateStyle = .long
// get the date time String from the date object
let mytime = formatter.string(from: currentDateTime) // October 8, 2016 at 10:48:53 PM
print(mytime)
}
I suggest you use this approach to Formatter Style (Swift 3):
formatter.dateStyle = DateFormatter.Style.full
formatter.timeStyle = DateFormatter.Style.long
In this case for a date as string with your locale:
let currentDate = Date()
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "----your locale here----")
formatter.dateStyle = DateFormatter.Style.full
let myDate = todayFormatter.string(from: currentDate)
print(myDate)
swift 4
==> Getting iOS device current time:-
let hh1 = Calendar.current.component(.hour, from: Date())
let mm1 = Calendar.current.component(.minute, from: Date())
let ss1 = Calendar.current.component(.second, from: Date())
print(hh1, ":", mm1, ":", ss1)
output: ---> 11 : 10: 25

How to fetch day, month and hour from NSDate in 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)

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