Get Current month & year and Passing to API iOS Swift? - ios

I have a func in which i have to pass current month & year parameters to Fetch API in Swift 3.If i pass hardCode in parameters i am getting the son response but i am not able to do it with current month & year. Code :-
func raffleNumberGenerate(){
let prs = [
"month":currentMonth,
"year" : currentYear,
"raffle_result": "1" as String
]
Service.StartWithoutLoading(prs as [String : AnyObject]?, onCompletion: { result in
let jsonResponseSingle = result as? NSDictionary
print(" JSON Response :- \(String(describing: jsonResponseSingle))"
}
Thanks in advance.

You have no values for currentMonth and currentYear, so you must make some.
func raffleNumberGenerate() {
let date = Date() // gets current date
let calendar = Calendar.current
let currentYear = calendar.component(.year, from: date) // gets current year (i.e. 2017)
let currentMonth = calendar.component(.month, from: date) // gets current month (i.e. 10)
let prs = [
"month":currentMonth,
"year" : currentYear,
"raffle_result": "1" as String
]
Service.StartWithoutLoading(prs as [String : AnyObject]?, onCompletion: { result in
let jsonResponseSingle = result as? NSDictionary
print(" JSON Response :- \(String(describing: jsonResponseSingle))"
}
}
Now you should be able to do whatever you need to do with the JSON. I should note that currentMonth and currentYear are now of type Int, if you need them as Strings you can just convert by saying String(currentMonth) and String(currentYear).

let today = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy"
let year = dateFormatter.string(from: today)
dateFormatter.dateFormat = "MM"
let month = dateFormatter.string(from: today)
e.g. year = 2017 month = 10
per #maddy
var calendar = NSCalendar.current
let today = Date()
let desiredComponents = Set<Calendar.Component>([.month, .year])
calendar.timeZone = TimeZone(identifier: "UTC")!
let components = calendar.dateComponents(desiredComponents, from: today)
components.year
components.month

Related

Create string array of dates from Dates range

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
}

Date will not display correctly

I am trying to make my date display such as "March 2nd, 2018 10:00pm". I tried "MM-dd-yyyy" and "yyyy-MM-dd hh:mm:ss" but it seems like none of these combinations are getting the date I desire.The function to pick the date is sendRequest and it is using a UIDatePicker.
func getCurrentDateTimeFromTimeStamp(timestamp:String)->String{
let date = NSDate(timeIntervalSince1970:Double(timestamp)!)
let formatter = DateFormatter()
formatter.dateFormat = "MMMM d, yyyy HH:mm a"
return formatter.string(from: date as Date)
}
let dateCellVar = request.timestamp
let dateString = dateCellVar.description
dateCell.textLabel?.text = self.getCurrentDateTimeFromTimeStamp(timestamp: dateString)
class Request {
var timestamp:Double
init(dict: [String: Any]) {
self.timestamp = dict["timestamp"] as? Double ?? 0.0
}
func sendRequest(){
print("HEY:")
guard let user = currentUser else { return }
print("USER: \(user.firstLastName)")
if let da = dateField.text{
print(da)
}
print(timeField.text)
print(locationField.text)
print(messageTextView.text)
guard let pickedDate = pickedDate else { return print("pickedDate") }
guard let date = dateField.text else { return print("pickedDate") }
guard let time = timeField.text else { return print("time") }
guard let location = locationField.text else { return print("location")}
let db = Database.database().reference()
let ref = db.child("requests").childByAutoId()
let data = [
"sender": user.uid,
"recipient": recipientUser.uid,
"name": user.firstLastName,
"photoURL": user.photoURL,
"location": location,
"date": date,
"time": time,
"pickedTimestamp": pickedDate.timeIntervalSince1970,
"message": messageTextView.text ?? "",
"status": "PENDING",
"timestamp": [".sv": "timestamp"]
] as [String:Any]
print("HEYO")
ref.setValue(data) { error, ref in
if error == nil {
print("Success")
} else {
print("Failed")
}
}
}
Based on your result, your timestamp is in milliseconds, not seconds. You need to divide by 1000.
You also have the wrong dateFormat. You want to use hh, not HH for the hour. H is for 24-hour time which makes no sense when using a for AM/PM. You should also avoid using dateFormat. Use dateStyle and timeStyle. Let the formatter give you a date formatted best for the user's locale.
Your code also does a lot of needless conversion. You get your timestamp as a Double and store it as a Double. But then your function to convert the timestamp you expect your number of seconds as a String which you then convert back to a Double. Avoid the needless use of a String.
To get the ordinal day, you can use Calendar to extract the day from your Date.
let date = Date()
let calendar = Calendar.current
let dateComponents = calendar.component(.day, from: date)
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .ordinal
let day = numberFormatter.string(from: dateComponents as NSNumber)
From there, you'd just code your date format with a DateFormatter and drop in the ordinal date you extracted above, like so:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM '\(String(describing: day!)),' yyyy h:mm a"
let dateString = "\(dateFormatter.string(from: date))"
print(dateString)
Additionally, the issue with your year probably stems from the number you're feeding it. timeIntervalSince1970 is expecting whole seconds, so make sure you're feeding it whole seconds.
init(timeIntervalSince1970: TimeInterval) Returns a date object
initialized relative to 00:00:00 UTC on 1 January 1970 by a given
number of seconds.
Adapted from this answer. Additionally, you may find this site helpful for formatting dates.

How to calculate how much time passed from the date with timezone?

I get from the server a date with this format:
2016-05-27 17:33:43+0400
Now, I want to detect, how much time passed since that date? For example 1 day 5 hours 10 minutes 20 seconds.
How can I do it? I know how to calculate this from the timestamp, but do not know how to convert this to a timestamp.
Can anyone help me with it?
For example:
Convert this 2016-05-27 17:33:43+0400 to 1464370423 this
Or maybe there are another solution. I just want to calculate how much time passed since that time
You can use NSDateComponents formatter to get the relative time between two dates. Regarding the date string format you need to use xx for the time zone part.
let dateStr = "2016-05-27 17:33:43+0400"
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ssxx"
formatter.calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierISO8601)
formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
if let date = formatter.dateFromString(dateStr) {
print(date) // "2016-05-27 13:33:00 +0000\n" -4hs
let dateComponentsFormatter = NSDateComponentsFormatter()
dateComponentsFormatter.allowedUnits = [.Day,.Hour,.Minute,.Second]
dateComponentsFormatter.unitsStyle = .Full
print(dateComponentsFormatter.stringFromDate(date, toDate: NSDate()) ?? "") // 6 days, 17 hours, 51 minutes, 29 seconds
}
given the input string you can convert it to a date and subsequently to an NSTimeInterval since the current time using the following.
let inputDate = "2016-05-27 17:33:43+0400"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ssZZZZZ"
if let aDate = dateFormatter.dateFromString(inputDate) {
let timeInterval = aDate.timeIntervalSinceNow
let dateComponentsFormatter = NSDateComponentsFormatter()
if let dateString = dateComponentsFormatter.stringFromTimeInterval(abs(timeInterval)) {
print ("Elapsed time=\(dateString)")
}
}
Output:
Elapsed time=6d 17:51:52
You can get the date as the timestamp in your question using aDate.timeIntervalSince1970
I suggest that this could help you: How to get the current time as datetime
You can get the current time and calculate the difference using the server time and your current time.
let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute, fromDate: date)
let hour = components.hour
let minutes = components.minute
Hope it helps.
This will tell you
"how many time"
passed since an event.
let date = Date()
let howManyTimePassed = date.timeIntervalSinceNow
TimeInterval is a typealias for a double, meaning its another way to say double. The value of the timeInterval represents seconds.
Try this class in Swift 5.1:
open class MyDateClass: NSObject {
private var result:MyDateTime!
init(dateStr: String, inputFormat: String) {
let formatter = DateFormatter()
formatter.dateFormat = inputFormat //"yyyy-MM-dd HH:mm:ss"
formatter.calendar = Calendar(identifier: .gregorian)
formatter.locale = Locale(identifier: "en_US_POSIX")
if let date = formatter.date(from: dateStr) {
let dateComponentsFormatter = DateComponentsFormatter()
dateComponentsFormatter.allowedUnits = [.year,.month,.day,.hour,.minute,.second]
dateComponentsFormatter.unitsStyle = .full
let strFromat = dateComponentsFormatter.string(from: date, to: Date()) ?? ""
var trimmedString = strFromat.replacingOccurrences(of: " ", with: "")
trimmedString = trimmedString.replacingOccurrences(of: "years", with: "")
trimmedString = trimmedString.replacingOccurrences(of: "months", with: "")
trimmedString = trimmedString.replacingOccurrences(of: "days", with: "")
trimmedString = trimmedString.replacingOccurrences(of: "hours", with: "")
trimmedString = trimmedString.replacingOccurrences(of: "minutes", with: "")
trimmedString = trimmedString.replacingOccurrences(of: "seconds", with: "")
let arr = trimmedString.split(separator: ",")
let result = MyDateTime(year: Int(arr[0]), month: Int(arr[1]), day: Int(arr[2]), hour: Int(arr[3]), minute: Int(arr[4]), second: Int(arr[5]))
self.result = result
}
}
func getDateTime() -> MyDateTime {
return result
}
}
public struct MyDateTime {
var year:Int?
var month:Int?
var day:Int?
var hour:Int?
var minute:Int?
var second:Int?
}
And this class works like this:
let myClass = MyDateClass(dateStr: "2016-05-27 17:33:43", inputFormat: "yyyy-MM-dd HH:mm:ss")
let time = myClass.getDateTime()
Now you can show time as you wish.

how to get 7 dates continuously with date and year

i have a module in that i have 7 buttons all the 7 buttons indicates date for action, i.e first button has current date, second button has tomorrow date, third button has day after tomorrow date likes go on till 7th button, i implemented code from one post to get info like that, but my problem is i can't convert date into string, i need to remove and replace the output value and send it to server
here my sample code :
func addDaystoGivenDate(baseDate:NSDate,NumberOfDaysToAdd:Int)->NSDate
{
let dateComponents = NSDateComponents()
let CurrentCalendar = NSCalendar.currentCalendar()
let CalendarOption = NSCalendarOptions()
dateComponents.day = NumberOfDaysToAdd
let newDate = CurrentCalendar.dateByAddingComponents(dateComponents, toDate: baseDate, options: CalendarOption)
return newDate!
}
override func viewDidLoad() {
let newDate = addDaystoGivenDate(NSDate(), NumberOfDaysToAdd: 1)
print(newDate)
}
my output is : 2016-04-06 08:35:59 +0000
but my expected output is : 06/04
can anyone solve my issues
You should be able to format your date right with this:
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd/MM"
let dateStr = dateFormatter.stringFromDate(newDate!)
// dateStr now contains the string "06/04"
Swift 3.0:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM"
let dateStr = dateFormatter.string(from: newDate)

iOS Swift converting calendar component int month to medium style string month

I want to display calendar in this format
to the user. One option is to use "string range" to get the individual calendar components. The second one is to get it using NSCalendar which to me looks like the better one (is it?). So my code is as below. But there are two problems.
I am not getting the local time form "hour & minute components"
I am getting month in Int. I want it to be in String (month in mediumStyle)
Anyone know how to get what I need? Image attached is what exactly I want to achieve. There I am using three UILabel one for "date", second for "month, year" and third for "time".
Any help would be appreciated.
var inputDateString = "Jun/12/2015 02:05 Am +05:00"
override func viewDidLoad() {
super.viewDidLoad()
let newDate = dateformatterDateString(inputDateString)
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute | .CalendarUnitMonth | .CalendarUnitYear | .CalendarUnitDay, fromDate: newDate!)
let hour = components.hour
let minutes = components.minute
let month = components.month
let year = components.year
let day = components.day
println(newDate)
println(components)
println(day) // 12
println(month) // 6 -----> Want to have "Jun" here
println(year) // 2015
println(hour) // 2 ------> Want to have the hour in the inputString i.e. 02
println(minutes) // 35 ------> Want to have the minute in the inputString i.e. 05
}
func dateformatterDateString(dateString: String) -> NSDate? {
let dateFormatter: NSDateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MMM/dd/yyyy hh:mm a Z"
// dateFormatter.timeZone = NSTimeZone(abbreviation: "UTC")
dateFormatter.timeZone = NSTimeZone.localTimeZone()
return dateFormatter.dateFromString(dateString)
}
You can use DateFormatter as follow:
extension Formatter {
static let monthMedium: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "LLL"
return formatter
}()
static let hour12: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "h"
return formatter
}()
static let minute0x: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "mm"
return formatter
}()
static let amPM: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "a"
return formatter
}()
}
extension Date {
var monthMedium: String { return Formatter.monthMedium.string(from: self) }
var hour12: String { return Formatter.hour12.string(from: self) }
var minute0x: String { return Formatter.minute0x.string(from: self) }
var amPM: String { return Formatter.amPM.string(from: self) }
}
let date = Date()
let dateMonth = date.monthMedium // "May"
let dateHour = date.hour12 // "1"
let dateMinute = date.minute0x // "18"
let dateAmPm = date.amPM // "PM"
NSDateFormatter has monthSymbols, shortMonthSymbols and veryShortSymbols properties.
So try this:
let dateFormatter: NSDateFormatter = NSDateFormatter()
let months = dateFormatter.shortMonthSymbols
let monthSymbol = months[month-1] as! String // month - from your date components
println(monthSymbol)
I am adding three types. Have a look.
//Todays Date
let todayDate = NSDate()
let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)!
let components = calendar.components(.CalendarUnitYear | .CalendarUnitMonth | .CalendarUnitDay, fromDate: todayDate)
var (year, month, date) = (components.year, components.month, components.day)
println("YEAR: \(year) MONTH: \(month) DATE: \(date)")
//Making a X mas Yr
let morningOfChristmasComponents = NSDateComponents()
morningOfChristmasComponents.year = 2014
morningOfChristmasComponents.month = 12
morningOfChristmasComponents.day = 25
morningOfChristmasComponents.hour = 7
morningOfChristmasComponents.minute = 0
morningOfChristmasComponents.second = 0
let morningOfChristmas = NSCalendar.currentCalendar().dateFromComponents(morningOfChristmasComponents)!
let formatter = NSDateFormatter()
formatter.dateStyle = NSDateFormatterStyle.LongStyle
formatter.timeStyle = .MediumStyle
let dateString = formatter.stringFromDate(morningOfChristmas)
print("dateString : \(dateString)")
//Current month - complete name
let dateFormatter: NSDateFormatter = NSDateFormatter()
let months = dateFormatter.monthSymbols
let monthSymbol = months[month-1] as! String
println("monthSymbol : \(monthSymbol)")
Print Results:
YEAR: 2015 MONTH: 10 DATE: 9
dateString : December 25, 2014 at 7:00:00 AM
monthSymbol : October
Update Swift 5.x Solution:
Today is Monday, 20 April, 2020
let date = Date() // get a current date instance
let dateFormatter = DateFormatter() // get a date formatter instance
let calendar = dateFormatter.calendar // get a calendar instance
Now you can get every index value of year, month, week, day everything what you want as follows:
let year = calendar?.component(.year, from: date) // Result: 2020
let month = calendar?.component(.month, from: date) // Result: 4
let week = calendar?.component(.weekOfMonth, from: date) // Result: 4
let day = calendar?.component(.day, from: date) // Result: 20
let weekday = calendar?.component(.weekday, from: date) // Result: 2
let weekdayOrdinal = calendar?.component(.weekdayOrdinal, from: date) // Result: 3
let weekOfYear = calendar?.component(.weekOfYear, from: date) // Result: 17
You can get an array of all month names like:
let monthsWithFullName = dateFormatter.monthSymbols // Result: ["January”, "February”, "March”, "April”, "May”, "June”, "July”, "August”, "September”, "October”, "November”, "December”]
let monthsWithShortName = dateFormatter.shortMonthSymbols // Result: ["Jan”, "Feb”, "Mar”, "Apr”, "May”, "Jun”, "Jul”, "Aug”, "Sep”, "Oct”, "Nov”, "Dec”]
You can format current date as you wish like:
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let todayWithTime = dateFormatter.string(from: date) // Result: "2020-04-20 06:17:29"
dateFormatter.dateFormat = "yyyy-MM-dd"
let onlyTodayDate = dateFormatter.string(from: date) // Result: "2020-04-20"
I think this is the most simpler and updated answer.
Swift 4.x Solution:
//if currentMonth = 1
DateFormatter().monthSymbols[currentMonth - 1]
Answer:
January
let now = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "LLLL"
let nameOfMonth = dateFormatter.string(from: now)

Resources