I have two dates, date1 and date2 and I want days between date1 and date 2
Example:
let date1 = 28-May-2019,
let date2 = 31-May-2019
The expected output
[Tue, Web Thr, Fri]
let date1Str = "28-May-2019"
let date2Str = "31-May-2019"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"
dateFormatter.locale = Locale(identifier: "en_US")
var date1 = dateFormatter.date(from:date1Str)!
var date2 = dateFormatter.date(from:date2Str)!
let dayFormatter = DateFormatter()
dayFormatter.dateFormat = "EEE"
while date1 <= date2 {
let dayInWeek = dayFormatter.string(from: date1)
print(dayInWeek)
date1 = Calendar.current.date(byAdding: .day, value: 1, to: date1)!
}
The following code gives you the days between two dates and should account for trickeries with the calendar.
let calendar = Calendar.current
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MMM-yyyy"
let dayFormatter = DateFormatter()
dayFormatter.dateFormat = "EEE"
let dateFrom = dateFormatter.date(from: "28-May-2019")!
let dateTo = dateFormatter.date(from: "31-May-2019")!
var days: [String] = []
var date = dateFrom
while date <= dateTo {
let day = dayFormatter.string(from: date)
days.append(day)
date = calendar.date(byAdding: .day, value: 1, to: date)!
}
print(days)
Try this -
func getWeekdays(dateOne firstDateStr: String, dateTwo secondDateStr: String) -> [String] {
let dateformatter = DateFormatter()
dateformatter.dateFormat = "dd-MMM-yyyy"
guard let firstDate = dateformatter.date(from: firstDateStr),
let secondDate = dateformatter.date(from: secondDateStr) else {
return []
}
let calendar = Calendar.current
let numberOfDays: Int
if firstDate > secondDate {
numberOfDays = (calendar.dateComponents([.day], from: secondDate, to: firstDate).day ?? 0)
} else {
numberOfDays = (calendar.dateComponents([.day], from: firstDate, to: secondDate).day ?? 0)
}
dateformatter.dateFormat = "EEE"
let days = (0...numberOfDays).compactMap { day -> String? in
if let date = calendar.date(byAdding: .day, value: day, to: firstDate) {
return dateformatter.string(from: date)
}
return nil
}
print(days)
return days
}
Related
I have got a date in this format..
2019-12-16 18:30:00 +0000
This is the code I have for that..
var utcTime = "\(dic["dueDate"]!)"
self.dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
self.dateFormatter.locale = Locale(identifier: "en_US")
let date = self.dateFormatter.date(from:utcTime)!
print(date)
I wanted to extract month and date from this string. i.e. from the above date string, I want 'December' & '16' separately.
There are several ways to get the expected result, as an option you can use this code with Calendar:
let utcTime = "2020-01-17T22:01:00"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
dateFormatter.locale = Locale(identifier: "en_US")
if let date = dateFormatter.date(from:utcTime) {
let monthInt = Calendar.current.component(.month, from: date)
let dayInt = Calendar.current.component(.day, from: date)
let monthStr = Calendar.current.monthSymbols[monthInt-1]
print(monthStr, dayInt)
}
Welcome to stack overflow.
You can try this :
let calendar = Calendar.current
calendar.component(.year, from: date)
calendar.component(.month, from: date)
calendar.component(.day, from: date)
Hope it helps...
Welcome to stack overflow. Please try this.
func getMonthAndDate(dateString: String) ->(month:String , day:String) {
guard let date = Date.getMonthAndDate(from: dateString, with: "yyyy-MM-dd'T'HH:mm:ss") else {
return ("","")
}
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM"
let month = dateFormatter.string(from: date)
dateFormatter.dateFormat = "dd"
let day = dateFormatter.string(from: date)
return (month,day)
}
extension Date {
static func getMonthAndDate(from str: String, with formatter: String) -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone.current//(abbreviation: "GMT") //Set timezone that you want
dateFormatter.locale = NSLocale.current
dateFormatter.dateFormat = formatter //Specify your format that you want
return dateFormatter.date(from: str)
}
}
Swift 5
Here is the extension you need It returns tuple having Month and date as you wanted to have
extension Date {
func getMonthAndDate() ->(month:String , day:String) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM"
let month = dateFormatter.string(from: self)
dateFormatter.dateFormat = "dd"
let day = dateFormatter.string(from: self)
return (month,day)
}
}
I give you example of month u can get date and month value separately ,
visit link for your format http://userguide.icu-project.org/formatparse/datetime
extension Date {
var month: String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM"
return dateFormatter.string(from: self)
}
}
you can use it in this way:
let date = Date()
let monthString = date.month
try same thing for date, I hope it will work for you... :)
this is an example from your code. I have stored month and day in separate string to show you. You can change according to your requirements.
var utcTime = "2019-12-16 18:30:00 +0000"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss z"
dateFormatter.locale = Locale(identifier: "en_US")
let date = dateFormatter.date(from:utcTime)!
print(date) //2019-12-16 18:30:00 +0000
dateFormatter.dateFormat = "MMMM"
let strMonth = dateFormatter.string(from: date)
print(strMonth) //December
dateFormatter.dateFormat = "dd"
let strDay = dateFormatter.string(from: date)
print(strDay) //16
Also you can use Calendar object to get date, month (gives you in digit) and year.
var utcTime = "2019-12-16 18:30:00 +0000"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss z"
dateFormatter.locale = Locale(identifier: "en_US")
let date = dateFormatter.date(from:utcTime)!
let calendarDate = Calendar.current.dateComponents([.day, .year, .month], from: date)
let day = calendarDate.day
print(day) //16
let month = calendarDate.month
print(month) //12
let year = calendarDate.year
print(year) //2019
You can get the day, month and year as follows
let yourDate = Calendar.current.dateComponents([.day, .year, .month], from: Date())
if let day = yourDate.day, let month = yourDate.month, let year = yourDate.year {
let monthName = Calendar.current.monthSymbols[month - 1]
// your code here
}
extension String {
func getMonthDay() -> (Int,Int) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ssZ"
let date = dateFormatter.date(from: self) ?? Date()
let calendar = Calendar.current
let month = calendar.component(.month, from: date)
let day = calendar.component(.day, from: date)
return (month, day)
}
}
I am formatting a randomly generated future date but it always returns nil even if the format of dateString is matching and has a value.
But if I try with only "(Date())" instead of newDate, it is successful.
let byDays = Int.random(in: 0...30)
var components = DateComponents()
components.day = byDays
let newDate = String(describing: Calendar.current.date(byAdding: components, to: Date()))
//give the current date output in string
let dateFormatterGet = DateFormatter()
dateFormatterGet.isLenient = true
dateFormatterGet.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
dateFormatterGet.locale = Locale(identifier: "en_US_POSIX")
//describe the new format
guard let date = dateFormatterGet.date(from: newDate) else {
return ""
}
let newDateFormatter = DateFormatter()
newDateFormatter.dateFormat = "MMM dd"
let newStr = newDateFormatter.string(from: date)
print(newStr)
I want the date optional(2019-07-23 17:44:23 +0000) to be printed as Jul 23.
I don't understand the purpose of String(describing: ... You can use the date from the Calendar right away:
func randomFutureDate() -> String? {
let day = Int.random(in: 0...30)
var components = DateComponents()
components.day = day
guard let date = Calendar.current.date(byAdding: components, to: Date()) else {
return nil
}
let newDateFormatter = DateFormatter()
newDateFormatter.dateFormat = "MMM dd"
return newDateFormatter.string(from: date)
}
I have Date() properties. startingAt and endingAt. And an array of Date(), which are alreadyRegistred. I have to create an array of strings with dates between startingAt and endingAt. StartingAt and endingAt are included and the last requirement is to exclude alreadyRegistred dates.
Do you have some elegant idea, how to do it? Thanks for help!
Edit: Maximum number of dates in final array will be about 7 days.
Dont forget that a Date is basically just a timestamp, and that you can have access to the addingTimeInterval(_:) method.
Knowing that, is very easy to do some calculation between two dates.
I do not have the whole knowledge about your required business logic, but here is a naive implementation that generates Dates between two dates. I'm sure you can run it in a playground and explore a little bit.
import UIKit
func intervalDates(from startingDate:Date, to endDate:Date, with interval:TimeInterval) -> [Date] {
guard interval > 0 else { return [] }
var dates:[Date] = []
var currentDate = startingDate
while currentDate <= endDate {
currentDate = currentDate.addingTimeInterval(interval)
dates.append(currentDate)
}
return dates
}
let startingDate = Date() // now
let endDate = Date(timeIntervalSinceNow: 3600 * 24 * 7) // one week from now
let intervalBetweenDates:TimeInterval = 3600 * 3// three hours
let dates:[Date] = intervalDates(from: startingDate, to: endDate, with: intervalBetweenDates)
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .long
dateFormatter.timeStyle = .long
let dateStrings = dates.map{dateFormatter.string(from: $0)}
print("NOW : \(startingDate)")
for (index, string) in dateStrings.enumerated() {
print("\(index) : \(string)")
}
print("END DATE : \(endDate)")
Try this and see:
// Start & End date string
let startingAt = "01/01/2018"
let endingAt = "08/03/2018"
// Sample date formatter
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"
// start and end date object from string dates
var startDate = dateFormatter.date(from: startingAt) ?? Date()
let endDate = dateFormatter.date(from: endingAt) ?? Date()
// String date array, to be excluded
let alreadyRegistred = ["01/01/2018", "15/01/2018", "10/02/2018", "20/02/2018", "05/03/2018"]
// Actual operational logic
var dateRange: [String] = []
while startDate <= endDate {
let stringDate = dateFormatter.string(from: startDate)
startDate = Calendar.current.date(byAdding: .day, value: 1, to: startDate) ?? Date()
if (alreadyRegistred.contains(stringDate)) {
continue
} else {
dateRange.append(stringDate)
}
}
print("Resulting Array - \(dateRange)")
Here is result:
Resulting Array - ["02/01/2018", "03/01/2018", "04/01/2018", "05/01/2018", "06/01/2018", "07/01/2018", "08/01/2018", "09/01/2018", "10/01/2018", "11/01/2018", "12/01/2018", "13/01/2018", "14/01/2018", "16/01/2018", "17/01/2018", "18/01/2018", "19/01/2018", "20/01/2018", "21/01/2018", "22/01/2018", "23/01/2018", "24/01/2018", "25/01/2018", "26/01/2018", "27/01/2018", "28/01/2018", "29/01/2018", "30/01/2018", "31/01/2018", "01/02/2018", "02/02/2018", "03/02/2018", "04/02/2018", "05/02/2018", "06/02/2018", "07/02/2018", "08/02/2018", "09/02/2018", "11/02/2018", "12/02/2018", "13/02/2018", "14/02/2018", "15/02/2018", "16/02/2018", "17/02/2018", "18/02/2018", "19/02/2018", "21/02/2018", "22/02/2018", "23/02/2018", "24/02/2018", "25/02/2018", "26/02/2018", "27/02/2018", "28/02/2018", "01/03/2018", "02/03/2018", "03/03/2018", "04/03/2018", "06/03/2018", "07/03/2018", "08/03/2018"]
let startDate = Date()
let endDate = Date().addingTimeInterval(24*60*60*10) // i did this to get the end date for now
var stringdateArray = [String]()
if let days = getNumberofDays(date1: startDate, date2: endDate) {
for i in 0...days-1 {
let date = startDate.addingTimeInterval(Double(i)*24*3600)
let stringDate = getStringDate(fromDate: date, havingFormat: "yyyy-MM-dd")
if !(alreadyRegisteredArray.contains(stringDate)) { // checking if already registered
stringdateArray.append(stringDate)
}
}
}
and our helper method
let dateFormatter = DateFormatter()
func getStringDate(fromDate: Date,havingFormat: String) -> String {
dateFormatter.dateFormat = havingFormat
dateFormatter.amSymbol = "AM"
dateFormatter.pmSymbol = "PM"
let date = dateFormatter.string(from: fromDate)
return date
}
func getNumberofDays(date1: Date, date2: Date) -> Int? {
let calendar = NSCalendar.current
let date1 = calendar.startOfDay(for: date1)
let date2 = calendar.startOfDay(for: date2)
let components = calendar.dateComponents([.day], from: date1, to: date2)
return components.day
}
How Can I convert dates into string format?
I am getting dates between two dates ( From to end date). and I was using this below method
class Dates {
static func printDatesBetweenInterval(_ startDate: Date, _ endDate: Date) {
var startDate = startDate
let calendar = Calendar.current
let fmt = DateFormatter()
fmt.dateFormat = "yyyy-MM-dd"
while startDate <= endDate {
print(fmt.string(from: startDate))
startDate = calendar.date(byAdding: .day, value: 1, to: startDate)!
}
}
static func dateFromString(_ dateString: String) -> Date {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
return dateFormatter.date(from: dateString)!
}}
and printing dates here
Dates.printDatesBetweenInterval(Dates.dateFromString("2017-10-02"), Dates.dateFromString("2017-10-9"))
result:
2017-10-02 2017-10-03 2017-10-04 2017-10-05 2017-10-06 2017-10-07 2017-10-08 2017-10-09
Now, I want pass this dates to String format to calendar (I am using FSCalendar lib into app). I want this format
example:
["2017-10-02", "2017-10-03", "2017-10-04", "2017-10-05", "2017-10-06", "2017-10-07", "2017-10-08", "2017-10-09"]
Can anyone guide me . Thanks
static func getDatesStringBetweenInterval(_ startDate: Date, _ endDate: Date)-> String {
var retval = "["
var startDate = startDate
let calendar = Calendar.current
let fmt = DateFormatter()
fmt.dateFormat = "yyyy-MM-dd"
while startDate <= endDate {
if startDate < endDate {
retval.append("\"\(fmt.string(from: startDate))\", ")
} else {
retval.append("\"\(fmt.string(from: startDate))\"")
}
startDate = calendar.date(byAdding: .day, value: 1, to: startDate)!
}
retval.append("]")
return retval
}
Usage:
let aDate = Dates.dateFromString("2017-01-01")
let bDate = Dates.dateFromString("2017-01-05")
let datesString = Dates.getDatesStringBetweenInterval(aDate, bDate)
print(datesString)
Return date string array from your function, like this:
class Dates {
static func printDatesBetweenInterval(_ startDate: Date, _ endDate: Date) -> [String] {
var startDate = startDate
let calendar = Calendar.current
let fmt = DateFormatter()
fmt.dateFormat = "yyyy-MM-dd"
var arrayDateString = [String]()
while startDate <= endDate {
let stringDate = fmt.string(from: startDate)
print("stringDate - \(stringDate)")
arrayDateString.append(stringDate)
startDate = calendar.date(byAdding: .day, value: 1, to: startDate)!
}
return arrayDateString
}
static func dateFromString(_ dateString: String) -> Date {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
return dateFormatter.date(from: dateString)!
}}
Now, print string array
let dateStringArray = Dates.printDatesBetweenInterval(Dates.dateFromString("2017-10-02"), Dates.dateFromString("2017-10-9"))
print("dateStringArray - \(dateStringArray)")
Edit:
Now, as you said, you've data in following format:
let dataArray = [
{ "hlddate": "07-Aug", "frmdt": "07-Aug-2017", "todt": "07-Aug-2017" },
{ "hlddate": "15-Aug", "frmdt": "15-Aug-2017", "todt": "15-Aug-2017" },
{ "hlddate": "10-Oct", "frmdt": "10-Oct-2017","todt": "31-Oct-2017" }
]
Try with following solution (Copy-paste, dataAray and class structure and see result):
class Dates {
static func dateFromString(dateString: String, webResponseDateFormat: String = "yyyy-MM-dd") -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = webResponseDateFormat
return dateFormatter.date(from: dateString)
}}
static func printDatesBetweenInterval(startDate: Date, endDate: Date, requiredDateFormat: String = "yyyy-MM-dd") -> [String] {
var startDate = startDate
let calendar = Calendar.current
let fmt = DateFormatter()
fmt.dateFormat = requiredDateFormat
var arrayDateString = [String]()
while startDate <= endDate {
let stringDate = fmt.string(from: startDate)
print("stringDate - \(stringDate)")
arrayDateString.append(stringDate)
startDate = calendar.date(byAdding: .day, value: 1, to: startDate)!
}
return arrayDateString
}
if let stringDateArray = dataArray as? [[String : String]] {
for arrayElement in stringDateArray {
if let startDateString = arrayElement["frmdt"], let startDate = Dates.dateFromString(dateString: startDateString, webResponseDateFormat: "dd-MMM-yyyy"), let endDateString = arrayElement["todt"], let endDate = Dates.dateFromString(dateString: endDateString, webResponseDateFormat: "dd-MMM-yyyy") {
let dateStringArray = Dates.printDatesBetweenInterval(startDate: startDate, endDate: endDate, )
print("\n\n**\ndateStringArray - \(dateStringArray)")
}
}
}
Final Update
// Actual data structure
let dataArray = ["07-8-2017","08-08-2017","10-09-2017","20-10-2017",21-10-2017","23-10-2017", etc..]
Use above method and change data in server response section and getting result.
if let Streams = jsonDict["data"] as! [AnyObject]? {
for arrayElement in Streams {
if let startDateString = arrayElement["frmdt"] {
self.somedateFromString = self.convertStringToDate(string: startDateString as! String)
if let endDateString = arrayElement["todt"] {
self.somedateEndString = self.convertStringToDate(string: endDateString as! String)
}
self.presentdays = Dates.printDatesBetweenInterval(Dates.dateFromString(self.somedateFromString), Dates.dateFromString(self.somedateEndString))
self.totalHolidays.append(contentsOf: self.presentdays)
}
}
}
I'm trying to get the start and end dates of the current month in dd/MM/yyyy format. I tried using extension as answered in this SO Question.But it seems like it's not what I want(the format is different and also it's giving me last month's last date and current month last but one date ). Can some one help me.
Extension Class:
extension Date {
func startOfMonth() -> Date? {
let comp: DateComponents = Calendar.current.dateComponents([.year, .month, .hour], from: Calendar.current.startOfDay(for: self))
return Calendar.current.date(from: comp)!
}
func endOfMonth() -> Date? {
var comp: DateComponents = Calendar.current.dateComponents([.month, .day, .hour], from: Calendar.current.startOfDay(for: self))
comp.month = 1
comp.day = -1
return Calendar.current.date(byAdding: comp, to: self.startOfMonth()!)
}
}
My Struct:
struct Constants{
// keys required for making a Login call (POST Method)
struct LoginKeys {
.....
}
struct RankingKeys {
static let DateFrom = String(describing: Date().startOfMonth()) //giving me 2016-11-30 16:00:00 +0000
static let DateTo = String(describing: Date().endOfMonth())
//2016-12-30 16:00:00 +0000
}
}
Expected Result:
DateFrom = "01/12/2016"
DateTo = "31/12/2016"
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!))
This is what I'm using. Pretty simple but it works.
extension Calendar {
func dayOfWeek(_ date: Date) -> Int {
var dayOfWeek = self.component(.weekday, from: date) + 1 - self.firstWeekday
if dayOfWeek <= 0 {
dayOfWeek += 7
}
return dayOfWeek
}
func startOfWeek(_ date: Date) -> Date {
return self.date(byAdding: DateComponents(day: -self.dayOfWeek(date) + 1), to: date)!
}
func endOfWeek(_ date: Date) -> Date {
return self.date(byAdding: DateComponents(day: 6), to: self.startOfWeek(date))!
}
func startOfMonth(_ date: Date) -> Date {
return self.date(from: self.dateComponents([.year, .month], from: date))!
}
func endOfMonth(_ date: Date) -> Date {
return self.date(byAdding: DateComponents(month: 1, day: -1), to: self.startOfMonth(date))!
}
func startOfQuarter(_ date: Date) -> Date {
let quarter = (self.component(.month, from: date) - 1) / 3 + 1
return self.date(from: DateComponents(year: self.component(.year, from: date), month: (quarter - 1) * 3 + 1))!
}
func endOfQuarter(_ date: Date) -> Date {
return self.date(byAdding: DateComponents(month: 3, day: -1), to: self.startOfQuarter(date))!
}
func startOfYear(_ date: Date) -> Date {
return self.date(from: self.dateComponents([.year], from: date))!
}
func endOfYear(_ date: Date) -> Date {
return self.date(from: DateComponents(year: self.component(.year, from: date), month: 12, day: 31))!
}
}
How to use
let calendar: Calendar = Calendar.current
let startDate = calendar.startOfMonth(Date())
print("startDate :: \(startDate)")
Here is an easy solution in create an extension for Date like following:
extension Date {
func startOfMonth() -> Date {
let interval = Calendar.current.dateInterval(of: .month, for: self)
return (interval?.start.toLocalTime())! // Without toLocalTime it give last months last date
}
func endOfMonth() -> Date {
let interval = Calendar.current.dateInterval(of: .month, for: self)
return interval!.end
}
// Convert UTC (or GMT) to local time
func toLocalTime() -> Date {
let timezone = TimeZone.current
let seconds = TimeInterval(timezone.secondsFromGMT(for: self))
return Date(timeInterval: seconds, since: self)
}}
And then call with your Date instance like that
print(Date().startOfMonth())
print(Date().endOfMonth())
With Swift 3 & iOS 10 the easiest way I found to do this is Calendar's dateInterval(of:for:):
guard let interval = calendar.dateInterval(of: .month, for: Date()) else { return }
Then use a date formatter to print the dates:
let formatter = DateFormatter()
formatter.dateFormat = "dd-MM-yyyy"
let dateText = formatter.string(from: interval.start)
This Extension Gives you expected output as per you want
Here I return date
extension NSDate {
func startOfMonth() -> NSDate? {
guard
let cal: NSCalendar = NSCalendar.currentCalendar(),
let comp: NSDateComponents = cal.components([.Year, .Month], fromDate: self) else { return nil }
comp.to12pm()
let dateformattor = NSDateFormatter()
dateformattor.dateFormat = "yyyy-MM-dd"
dateformattor.timeZone = NSTimeZone.localTimeZone()
let dt2 = dateformattor.stringFromDate(cal.dateFromComponents(comp)!)
print(dt2)
dateformattor.dateFormat = "yyyy-MM-dd"
dateformattor.timeZone = NSTimeZone.init(abbreviation: "UTC")
return dateformattor.dateFromString(dt2)
}
func endOfMonth() -> NSDate? {
guard
let cal: NSCalendar = NSCalendar.currentCalendar(),
let comp: NSDateComponents = NSDateComponents() else { return nil }
comp.month = 1
comp.day = -1
comp.to12pm()
let dateformattor = NSDateFormatter()
dateformattor.dateFormat = "yyyy-MM-dd"
dateformattor.timeZone = NSTimeZone.localTimeZone()
let dt2 = dateformattor.stringFromDate(cal.dateByAddingComponents(comp, toDate: self.startOfMonth()!, options: [])!)
dateformattor.dateFormat = "yyyy-MM-dd"
dateformattor.timeZone = NSTimeZone.init(abbreviation: "UTC")
return dateformattor.dateFromString(dt2)
}
}
internal extension NSDateComponents {
func to12pm() {
self.hour = 12
self.minute = 0
self.second = 0
}
}
**OUTPUT :- **
Start Date of Month :- 2016-12-01 00:00:00 +0000
End Date of Month :- 2016-12-31 00:00:00 +0000
For the sake of completeness, the API dateInterval(of:start:interval:for:) of Calendar assigns the start date and interval (in seconds) of the current month to the inout parameters.
The date formatter considers the current time zone.
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "dd/MM/yyyy"
var startDate = Date()
var interval = TimeInterval()
Calendar.current.dateInterval(of: .month, start: &startDate, interval: &interval, for: Date())
let endDate = Calendar.current.date(byAdding: .second, value: Int(interval) - 1, to: startDate)!
let fromDate = formatter.string(from: startDate)
let toDate = formatter.string(from: endDate)
print(fromDate, toDate)