Basically i have a tableView where i save a date... then i want to save another date, and push the first date from '0' in array to '1' position, while populating '0' with new date
let now = Date()
var date = ""
This creates a date ^^
var list = [ String(date) ]
this is the array ^^
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .short
// print(dateFormatter.string(from: now))
date = (dateFormatter.string(from: now))
This turns raw date into an easy to read string ^^
I want to make a function that Saves that string in the array, moves it down and creates a new one with new date
You can declare the array of date strings like this
var dates = [String]()
then create the date string
let now = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM dd,yyyy"
let dateStr = dateFormatter.string(from: now)
then insert it in the array at index 0
dates.insert(dateStr, at: 0)
Related
I would like to format my dates to not have zeros in the beginning.
For example
04/03/20 -> swift should display as 4/3/20
I basically want to remove the zero that may be in front of the day, month, or year. The purpose of this is not for style purposes but for me to access data in a JSON. That's why it needs to be soo specific.
You can get by using Date & DateFormatter
let formatter = DateFormatter()
formatter.dateFormat = "dd/MM/yy" // change formate as per your requirement
let date = formatter.date(from: "04/03/20") //change "04/03/20" to your input string
formatter.dateFormat = "d/M/yy"
let dateString = formatter.string(from: date!)
print(dateString) // 4/3/20
let date = "04/03/20"
let parts = date.split(separator: "/")
var newDate = ""
for i in 0..<parts.count {
newDate = "\(newDate)\(i == 0 ? "" :"/")\(Int(parts[i])!)"
}
print(newDate) //Result - 4/3/20
I am removing the current time from the current time and trying to find the minute difference. But it says 10/09/2019 13:13 and there is an error in the extraction process (I want to print as 1313) .1313 I can perform the extraction process. How do I print this data the way I want? I want to print dateFormat = "HHmm". In timertext2New.text, dateFormat = "dd / MM / yyyy HH: mm" like this. But I want to save it in HHmm format.
save12 output: 05/09/2019 10:48 but I want it to be "1048" . To perform extraction.
let formatter = DateFormatter()
formatter.dateFormat = "dd/MM/yyyy HH:mm"
timertext2New.text = formatter.string(from: datePicker.date)
let timehafıza2 = String(self.timertext2New.text!)
let df2 = DateFormatter()
df2.dateFormat = "HHmm"
var str2 = df2.string(from: Date())
str2 = timehafıza2
UserDefaults.standard.setValue(str2, forKey: "timertext2")
override func viewDidLoad() {
super.viewDidLoad()
let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HHmm"
let hour = dateFormatter.string(from: date)
var save12 = UserDefaults.standard.integer(forKey: "timertext2")
var fark : Int = (Int(hour)! - Int(save12))
}
Your code is pretty confusing and cannot work
You convert a date from a date picker with format "dd/MM/yyyy HH:mm"
Then you create a string with format "HHmm" from the current date which will be destroyed immediately because
You overwrite this string with the dd/MM/yyyy HH:mm string and save it to UserDefaults
Later you read the value from UserDefaults as integer which returns 0 because the "dd/MM/yyyy HH:mm" format is not representable by an integer.
My suggestion is to save all dates as Date and perform the date math with the dedicated methods of Calendar
I have this array
var bookTimeArray = [BookTime]()
BookTime class contains followings
var time : String = ""
var status : String = ""
var booked_by : String = ""
Now i need to sort the array bookTimeArray by seeing the BookTime.time variable.
Time variable may contain one time from "12AM" to "11PM"
The object need to be sorted in following pattern
["12AM", "1AM", "2AM", "3AM", "4AM", "5AM", "6AM", "7AM", "8AM", "9AM", "10AM", "11AM", "12PM", "1PM", "2PM", "3PM", "4PM", "5PM", "6PM", "7PM", "8PM", "9PM","10PM", "11PM"]
if bookTimeArray has 5 object
bookTimeArray[0].time = "10AM"
bookTimeArray[1].time = "6AM"
bookTimeArray[2].time = "9AM"
bookTimeArray[3].time = "6PM"
bookTimeArray[4].time = "9PM"
Expected output
bookTimeArray[0].time = "6AM"
bookTimeArray[1].time = "9AM"
bookTimeArray[2].time = "10AM"
bookTimeArray[3].time = "6PM"
bookTimeArray[4].time = "9PM"
I cant figure out how to achieve this. Help me out :(
You can do it this way:
// First create a DateFormatter object to convert your time strings to Date objects so you can compare between them.
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "ha"
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
// Then you only need to sort the bookTimeArray by *time* property after converting *time* string to a Date object using the dateFormatter that we've created above.
let sortedBooks = bookTimeArray.sorted { dateFormatter.date(from: $0.time)! < dateFormatter.date(from: $1.time)! }
You can use dateFormatter for creating Date objects from your String property and then you can sort your array by these Dates
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "ha" // format 1AM, 2AM, 12PM, ...
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
Sorting:
bookTimeArray.sort { bookTime1, bookTime2 in
guard let date1 = dateFormatter.date(from: bookTime1.time), let date2 = dateFormatter.date(from: bookTime2.time) else { return false }
return date1 < date2
}
Hope this will help:
// Custom models array
let dataArray = [Class(fileID:1),Class(fileID:2),Class(fileID:3)]
// here is sorting code
dataArray.sorted({ $0.fileID > $1.fileID })
I am trying to convert fajerTime to NSDate. When I compile the project the dateValue is nil. Any idea how to fix this issue?
if prayerCommingFromAdan.id == 0 && prayerCommingFromAdan.ringToneId != 0{
// NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(YourClassName.methodOfReceivedNotification(_:)), name:"NotificationIdentifier", object: nil)
let fajerTime = "\(prayer0.time[0...1]):\(prayer0.time[3...4])" as String
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
dateFormatter.timeZone = NSTimeZone.localTimeZone()
// convert string into date
let dateValue = dateFormatter.dateFromString(fajerTime) as NSDate!
print(dateValue)
var dateComparisionResult:NSComparisonResult = NSDate().compare(dateValue)
if dateComparisionResult == NSComparisonResult.OrderedDescending {
addNotificationAlarm(year, month: month, day: day, hour: prayer0.time[0...1], minutes: prayer0.time[3...4], soundId: prayerCommingFromAdan.ringToneId, notificationBody: "It is al fajr adan")
}
The problem seems be the format of fajerTime. It looks like fajerTime is a time string, e.g. 12:34, whereas the date formatter is configured to accept string containing a month, day and year, e.g. 24-07-2016.
You need to format fajerTime to include the year, month and day, as well as the time. Also configure the date formatter to accept the full date and time.
Assuming prayer0 is an array, you will also need to combine the elements into a string, using joinWithSeparator.
e.g.
let hours = prayer0.time[0...1].joinWithSeparator("")
let minutes = prayer0.time[3...4].joinWithSeparator("")
let fajerTime = "\(month)-\(day)-\(year) \(hours):\(minutes)"
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy hh:mm"
dateFormatter.timeZone = NSTimeZone.localTimeZone()
// convert string into date
let dateValue = dateFormatter.dateFromString(fajerTime) as NSDate!
Please follow example (Swift 3):
let dateStr = "2016-01-15 20:10:01 +0000"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
let myDate = dateFormatter.date(from: dateStr)
Keep in mind:
Date format e.g. "yyyy-MM-dd HH:mm:ss Z" must match the date string pattern
In your case, your date string contains only time, yet, your date
formatter contains only date
When using dateFormatter.date() there is no need to cast it to Date as it returns a Date:
Helpful website for date formats:
http://nsdateformatter.com/
I've got a string (eg. "2014-11-06 16:32:01")
I want to turn this format into an NSDate object.
Here's what I'm doing:
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
var date = dateFormatter.dateFromString("2014-11-06 16:32:01")!
var myCalendar:NSCalendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)!
var myComponents = myCalendar.components(NSCalendarUnit.WeekdayOrdinalCalendarUnit, fromDate: date)
var year = myComponents.year
var month = myComponents.month
var day = myComponents.day
year, month, and day are each valued at 9223372036854775807. Am I getting the dateFormat wrong?
The date format is correct. But you have to specify all wanted units in the
myCalendar.components(...) call. All other components are set to NSNotFound aka NSIntegerMax,
which is 2^63 - 1 = 9223372036854775807 on the 64-bit architecture.
This should work:
var myComponents = myCalendar.components(.YearCalendarUnit | .MonthCalendarUnit | .DayCalendarUnit, fromDate: date)
static func convertStringToNSDate(dateStr: String) -> NSDate
{
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy'-'MM'-'dd HH':'mm':'ss '+0000'"
let date = dateFormatter.dateFromString(dateStr)
return date!
}
On my code I am using that method in order to convert a string to NSDate. The only thing that you need to do is to change the dateFormat attribute to be the same as the date's format you want to convert.