I have made a functioning app and part of it includes formatting the date from a date picker.
I need to change the first day of the week as the week days are being displayed as "1" - "7". However, day 1 is currently Sunday and I need day 1 to be Monday and Sunday as day 7.
The code for my date formatter and picker are below:
var chosenDate = self.datePicker.date
var formatter = NSDateFormatter()
formatter.dateFormat = "ewYY"
let day = formatter.stringFromDate(chosenDate)
let dateResult = "\(day)"
DestViewController.date = dateResult
I got all of my date formatting info from this page:
http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns
I just can't seem to work out how to change this first day of the week?
Many thanks in advance
Mark.
Here is good example in how to manipulate date in swift. you can change the code to fit it better for what you may need, but right now it does what you need.
// Playground - noun: a place where people can play
// Setup the calendar object
let calendar = NSCalendar.currentCalendar()
// Set up date object
let date = NSDate()
// Create an NSDate for the first and last day of the month
let components = NSCalendar.currentCalendar().components(NSCalendarUnit.CalendarUnitMonth, fromDate: date)
components.month
// Getting the First and Last date of the month
components.day = 1
let firstDateOfMonth: NSDate = calendar.dateFromComponents(components)!
components.month += 1
components.day = 0
let lastDateOfMonth: NSDate = calendar.dateFromComponents(components)!
var unitFlags = NSCalendarUnit.WeekOfMonthCalendarUnit |
NSCalendarUnit.WeekdayCalendarUnit |
NSCalendarUnit.CalendarUnitDay
let firstDateComponents = calendar.components(unitFlags, fromDate: firstDateOfMonth)
let lastDateComponents = calendar.components(unitFlags, fromDate: lastDateOfMonth)
// Sun = 1, Sat = 7
let firstWeek = firstDateComponents.weekOfMonth
let lastWeek = lastDateComponents.weekOfMonth
let numOfDatesToPrepend = firstDateComponents.weekday - 1
let numOfDatesToAppend = 7 - lastDateComponents.weekday + (6 - lastDateComponents.weekOfMonth) * 7
let startDate: NSDate = calendar.dateByAddingUnit(NSCalendarUnit.CalendarUnitDay, value: -numOfDatesToPrepend, toDate: firstDateOfMonth, options: nil)!
let endDate: NSDate = calendar.dateByAddingUnit(NSCalendarUnit.CalendarUnitDay, value: numOfDatesToAppend, toDate: lastDateOfMonth, options: nil)!
Array(map(0..<42) {
calendar.dateByAddingUnit(NSCalendarUnit.CalendarUnitDay, value: $0, toDate: startDate, options: nil)!
})
"\(components.year)"
//var dateString = stringFromDate(NSDate())// change to your date format
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "EE"
var dateString = dateFormatter.stringFromDate(NSDate())
var xdate = dateFormatter.dateFromString(dateString)
//var someDate = dateFormatter.dateString
println(dateString)
this will output::
"Thu"
Related
I want to print date [1,2,3.... current date] but not getting correct result.
Because when I set first day is "1" in my code, the output in [2,3,4]. And when I set day is "0". It result show correct but show an extra date [1,2,3,4,5]. And today is 4th October 2016, as my time zone.
let date = NSDate()
let components = NSCalendar.currentCalendar().components([.Day , .Month , .Year], fromDate: date)
let year = components.year
let month = components.month
let day = 1 // Output is [2,3,4]
// let day = 0 than o/p [1,2,3,4,5]
dateFormatatter.dateFormat = "MMMM yyyy"
monthNameLabel.text = dateFormatatter.stringFromDate(date)
startDate.year = year
startDate.month = month
startDate.day = day
let startDateNSDate = calendar.dateFromComponents(startDate)!
var dateStart = startDateNSDate // first date
let endDate = NSDate() // last date
dateFormatatter.dateFormat = "dd"
while dateStart.compare(endDate) != .OrderedDescending {
// print(fmt.stringFromDate(date))
// Advance by one day:
dateStart = calendar.dateByAddingUnit(.Day, value: 1, toDate: dateStart, options: [])!
let dateFormat1 = NSDateFormatter()
dateFormat1.dateFormat = "dd-MM-yyyy"
dateArrayCalendar.addObject(dateFormatatter.stringFromDate(dateStart))
dateArrayForCompare.addObject(dateFormat1.stringFromDate(dateStart))
}
And I want result like this [1,2,3,4]
And Same issue Here
let componentsForCompare = calendar.components([.Year, .Month], fromDate: date)
let startOfMonth = calendar.dateFromComponents(componentsForCompare)!
print(startOfMonth)//2016-09-30 18:30:00 +0000
print(dateFormatatter.stringFromDate(startOfMonth)) //01
Its give different Outputs
You need to increment your date at the end of the while loop, rather than at the start:
while dateStart.compare(endDate) != .OrderedDescending {
// print(fmt.stringFromDate(date))
// Advance by one day:
let dateFormat1 = NSDateFormatter()
dateFormat1.dateFormat = "dd-MM-yyyy"
dateArrayCalendar.addObject(dateFormatatter.stringFromDate(dateStart))
dateArrayForCompare.addObject(dateFormat1.stringFromDate(dateStart))
dateStart = calendar.dateByAddingUnit(.Day, value: 1, toDate: dateStart, options: [])!
}
I am working on get start and end date from today’s date.
I am getting start and end date of current month by using
formula given by Martin R
Get first and last day of month
It is working perfectly.
My issue is how to put my custom value in this line
let components1 = calendar.components([.Year, .Month], fromDate: date)
Can I replace my custom month value to this code?
My requirement is:
I have one tableView for months like January, etc.
When I will click TableView I am getting current month according to tableview.
Suppose I click on January, I will get value 1.
So how to get start and end date of month using my custom month value?
My Code
let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd MM yyyy"
//To Get Start Date of Month
let components1 = calendar.components([.Year,.Day], fromDate: date)
components1.month = 3
let startOfMonth = calendar.dateFromComponents(components1)!
txtStartDate.text = dateFormatter.stringFromDate(startOfMonth)
try this code:
let calendar = NSCalendar.currentCalendar()
let date = "January 2016" // custom value
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MMMM yyyy"
let components = calendar.components([.Year, .Month, .Day], fromDate: dateFormatter.dateFromString(date)!)
let startOfMonth = calendar.dateFromComponents(components)!
dateFormatter.dateFormat = "MM"
print(dateFormatter.stringFromDate(startOfMonth))
//NSLog("%# : %#", startOfMonth,dateFormatter.stringFromDate(startOfMonth));
Output:
01
I am answering my own question
temp number is month number like if January it will considered as 1.
plz go through this solution to get start and end date from custom values
thanks #Martin R
let calendar = NSCalendar.currentCalendar()
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd MM yyyy"
//To Get Start Date of Month
let components1 = calendar.components([.Year], fromDate: NSDate())
components1.month = Int(tempNumber!)!
let startOfMonth = calendar.dateFromComponents(components1)!
txtStartDate.text = dateFormatter.stringFromDate(startOfMonth)
//To Get End Date of Month
let comps2 = NSDateComponents()
comps2.month = 1
comps2.day = -1
let endOfMonth = calendar.dateByAddingComponents(comps2, toDate: startOfMonth, options: [])!
txtEndDate.text = dateFormatter.stringFromDate(endOfMonth)
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
I am trying to compare two NSDates to understand if they are in the same day or not. These are the two dates (the second one is always the current date, NSDate()):
2015-08-23 22:00:00 +0000
2015-08-23 19:13:45 +0000
It seems obvious that the dates are in the same day, as 23 = 23. However I can't seem to be able to establish this in the code. I tried:
1)
let date = tripObject["tripDate"] as! NSDate
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let str = dateFormatter.stringFromDate(date)
let date2 = NSDate()
let dateFormatter2 = NSDateFormatter()
dateFormatter2.dateFormat = "yyyy-MM-dd"
let str2 = dateFormatter2.stringFromDate(date2)
println(". \(str) and \(str2) .")
This gives 2015-08-24 and 2015-08-23
2)
let dateComponents = NSCalendar.currentCalendar().components(.CalendarUnitYear | .CalendarUnitMonth | .CalendarUnitDay, fromDate: tripObject["tripDate"] as! NSDate)
let dateComponents2 = NSCalendar.currentCalendar().components(.CalendarUnitYear | .CalendarUnitMonth | .CalendarUnitDay, fromDate: NSDate())
This gives different day components.
3)
if NSCalendar.currentCalendar().isDate(firstDate!, inSameDayAsDate: secondDate!){
4)
if NSCalendar.currentCalendar().isDateInToday(the NSDate) {
Both 3 and 4 fail.
I am totally lost, any ideas?
NSCalendar has a method isDate:equalToDate:toUnitGranularity: which does exactly what you need
date1 and date2 are the NSDate instances to be compared, the result is Bool
let calendar = NSCalendar.currentCalendar()
calendar.timeZone = NSTimeZone(forSecondsFromGMT: 0)
let datesAreInTheSameDay = calendar.isDate(date1, equalToDate: date2, toUnitGranularity: .CalendarUnitDay | .CalendarUnitMonth | .CalendarUnitYear)
Swift 2:
let datesAreInTheSameDay = calendar.isDate(date1, equalToDate: date2, toUnitGranularity: [.Day, .Month, .Year])
Swift 3:
var calendar = Calendar.current
calendar.timeZone = TimeZone(secondsFromGMT: 0)!
let datesAreInTheSameDay = calendar.isDate(date1, equalTo: date2, toGranularity:.day)
You can convert both dates to start of the day and then use compare method of NSDate to compare them
let date1StartOfTheDay = NSCalendar.currentCalendar().startOfDayForDate(date)
let date2StartOfTheDay = NSCalendar.currentCalendar().startOfDayForDate(date2
if date1StartOfTheDay.compare(date2StartOfTheDay) == OrderedSame
{
//same dates
}
You can use this extension:
extension NSDate {
func isEqualToDate2(dateToCompare : NSDate) -> Bool {
//Declare Variables
var isEqualTo = false
//Compare Values
if self.compare(dateToCompare) == NSComparisonResult.OrderedSame {
isEqualTo = true
}
//Return Result
return isEqualTo
}
}
like:
if date1.isEqualToDate2(date2) {
...
}
I have dateformat string like this "2015-03-09".How do i get next 10 days date from current date?any help will be appreciated.thanks in advance
For a purely Swift 3 solution:
Calendar.current.date(byAdding: .day, value: 10, to: Date())
Here's how to get a date 10 days from now, using built-in date modification method .dateByAddingUnit
If all 10 days (dates) are required, can be looped by "value:10" part and added to array.
var tenDaysfromNow: NSDate {
return NSCalendar.currentCalendar().dateByAddingUnit(.Day, value: 10, toDate: NSDate(), options: [])!
}
print(tenDaysfromNow)
And for Swift3:
var tenDaysfromNow: Date {
return (Calendar.current as NSCalendar).date(byAdding: .day, value: 10, to: Date(), options: [])!
}
You can use the dateByAddingTimeInterval() method for this.
var dateStr = "2015-03-09"
var formatter = NSDateFormatter()
formatter.dateFormat = "YYYY-MM-dd"
var currDate = formatter.dateFromString(dateStr)
for i in 1...10
{
var interval = NSTimeInterval(60 * 60 * 24 * i)
var newDate = currDate?.dateByAddingTimeInterval(interval)
println(newDate)
}
EDIT:
As mentioned by #Martin R in the comments, it'll be better to use dateByAddingComponents() of NSCalendar class:
var calendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)
var dateComponent = NSDateComponents()
for i in 1...10
{
dateComponent.day = i
var newDate = calendar?.dateByAddingComponents(dateComponent, toDate: currDate!, options:nil)
println(newDate)
}
There is a function 'dateByAddingTimeInterval()' for an NSDate object. With this, you can create a NSDate from your date string. Then add 10 days = 10*24*60*60 to get next 10 days NSDate value
let today : NSDate = ....
let next10days = today.dateByAddingTimeInterval(10*60*60*24); //interval = seconds
//then you convert back to your date string format if you want, by using NSDateFormatter
To avoid problem with Daylighttime saving (#MartinR):
let cal = NSCalendar(calendarIdentifier: NSGregorianCalendar)
let next10Days = cal.dateByAddingUnit(NSCalendarUnit.DayCalendarUnit, value: 10, toDate: today, options: nil)
Here is a swift 4/5 version of the answer by #MidhunMP
var dateStr = "2015-03-09"
var formatter = DateFormatter()
formatter.dateFormat = "YYYY-MM-dd"
var calendar = Calendar(identifier: .gregorian)
var dateComponent = DateComponents()
if let currDate = formatter.date(from: dateStr) {
for i in 1...10 {
let newDate = calendar.date(byAdding: .day, value: i, to: currDate)
print(newDate)
}
}
For Swift 3:
let now = NSDate()
let plusTen = now.dateByAddingDays(10)