How to get first date of month? - ios

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)

Related

Date not getting correctly using NSDate In Swift

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: [])!
}

dateFromComponents gives Wrong date

I am trying to get a Date object from NSDateComponents, but Calendar.date(from: Components) is giving a date one day before the date that was in my original components.
let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
let dateComponents = calendar!.components([.Year , .Month , .Weekday, .Day], fromDate: NSDate())
dateComponents.year = 2015
dateComponents.month = 9
dateComponents.day = 1
po calendar!.dateFromComponents(dateComponents)
▿ Optional(2015-08-31 18:30:00 +0000)
- Some : 2015-08-31 18:30:00 +0000
Set the time zone with calendar object to UTC, and the try to get Date from the calendar.
calendar.timeZone = NSTimeZone(name: "UTC")!
It's giving you the UTC time zone, Just convert the Date by usning NSDateFormatter like this, you will get your answer -
let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
let dateComponents = calendar!.components([.Year , .Month , .Weekday, .Day], fromDate: NSDate())
dateComponents.year = 2015
dateComponents.month = 9
dateComponents.day = 1
let df = NSDateFormatter()
df.dateFormat = "yyyy-MM-dd"
let datestring = df.stringFromDate(calendar!.dateFromComponents(dateComponents)!)
print(datestring)

How can I convert the 24 hour time format to 12 hour time format?

I can get the 24 hour style time, but how do I get the 12 hour format with the am and pm?
let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Hour, .Minute, .Second], fromDate: date)
let hour = components.hour
let minutes = components.minute
As you say, you should use NSDateFormatter for your desired format. Hope this will help you.
let date = NSDate()
let formatter = NSDateFormatter()
formatter.dateFormat = "hh:mm a"
let time = formatter.stringFromDate(date)
For more information about date formatter see NSDateFormatter
Swift 3.1 Answer
let date = Date() //Jun 1, 2017, 10:22 AM"
let formatter = DateFormatter() //<NSDateFormatter: 0x608000244380>
formatter.dateFormat = "hh:mm a" //<NSDateFormatter: 0x608000244380>
let time = formatter.string(from: date) //"10:22 AM"
Time format must be in 'hh' not HH
formatter.dateFormat = "hh:mm a"
let str=dict["startDateTime"] as! String //if the date is in the array
let str="16:00" //if you want to use static date
let index=str.index(str.startIndex, offsetBy: 11)
let end_index=str.index(str.endIndex, offsetBy:-3)
let dateAsString = str[index ..< end_index]
let dateFormatter=DateFormatter()
dateFormatter.dateFormat="HH:mm"
let date = dateFormatter.date(from: String(dateAsString))
dateFormatter.dateFormat = "h:mm a"
let Date12 = dateFormatter.string(from: date!)
print(Date12)

Swift - Get date from day of year

We can get day of year for date using below line.
let day = cal.ordinalityOfUnit(.Day, inUnit: .Year, forDate: date)
But how can we get the date from day of year?
If you know the year you can get DateComponents date property as follow:
extension Calendar {
static let iso8601 = Calendar(identifier: .iso8601)
}
let now = Date()
let day = Calendar.iso8601.ordinality(of: .day, in: .year, for: now)! // 121
let year = Calendar.iso8601.component(.year, from: now) // 2017
let date = DateComponents(calendar: .iso8601, year: year, day: day).date // "May 1, 2017, 12:00 AM"
or using DateFormatter
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy D"
if let date = dateFormatter.date(from: "\(year) \(day)") {
dateFormatter.dateStyle = .medium
dateFormatter.timeStyle = .short
dateFormatter.string(from: date) // "May 1, 2017, 12:00 AM"
}
You cannot go the other way. Going from a date to a day of the year discards all other information, you are left with only the day of the year (you no longer know what year). To go back to a full date you would have to make assumptions about the year the day was in.
The answer that #LeoDabus gave is more succinct than this, so it is perhaps the better choice. Having said that, this is the code that I would have used:
let dateComponents = NSDateComponents();
dateComponents.year = 2015
dateComponents.day = day
let calendar = NSCalendar.currentCalendar()
let date = calendar.dateFromComponents(dateComponents)
Updated for Swift 4:
let dateComponents = NSDateComponents();
dateComponents.year = 2018
dateComponents.day = someDay
let calendar = NSCalendar.current
let date = calendar.date(from: dateComponents as DateComponents)

How to change the first day of week in Swift

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"

Resources