How to format dates without the '0' in the beginning with Swift? - swift

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

Related

Swift - Find Difference Between Upcoming Time and Current Time

I have a date/time returning from an API that is formatted in RFC 3339. RFC3399 looks like the following: "2021-07-24T22:36:39-04:00"
To be even more clear, it can be generated directly in swift doing something like the following:
let RFC3339DateFormatter = DateFormatter()
RFC3339DateFormatter.locale = Locale(identifier: "en_US_POSIX")
RFC3339DateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
RFC3339DateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
/* 39 minutes and 57 seconds after the 16th hour of December 19th, 1996 with an offset of -08:00 from UTC (Pacific Standard Time) */
let string = "1996-12-19T16:39:57-08:00"
let date = RFC3339DateFormatter.date(from: string)
My question is, how can I find the difference between times stored in RFC 3339 format in String variables.
For example, I have one variable titled currentTime that returns the current date/time in RFC 3339 format, and I have data from my API that returns a future time in RFC 3339 format. How can I subtract the time returned in each of these to determine the difference between the two?
Also, the date returned is not a concern to me. Only need to find the difference in time.
once you have your dates from the strings, you coud do something like this using component:
EDIT, using Alexander suggestion:
struct ContentView: View {
#State var timediff = ""
var body: some View {
Text(timediff)
.onAppear {
let RFC3339DateFormatter = DateFormatter()
RFC3339DateFormatter.locale = Locale(identifier: "en_US_POSIX")
RFC3339DateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
RFC3339DateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
let string1 = "1996-12-19T16:39:57-08:00"
let date1 = RFC3339DateFormatter.date(from: string1)
let string2 = "1996-12-19T13:19:27-08:00"
let date2 = RFC3339DateFormatter.date(from: string2)
if let d1 = date1, let d2 = date2 {
let result = Calendar.current.dateComponents([.hour, .minute], from: d1, to: d2)
timediff = result.description
}
}
}

How to format stringDateJson to label? [duplicate]

This question already has answers here:
Convert string to date in Swift
(18 answers)
Closed 1 year ago.
var str = "2021-05-23T06:35:47.409Z"
var formatter = DateFormatter()
formatter.dateFormat = "MMM d yyyy, h:mm:ss a"
let formattedtoDate = formatter.date(from: str)
let formattedtoString = formatter.string(from: formattedtoDate) //Error Cannot force unwrap value of non-optional type 'String'
cell.date_announce.text = formattedtoString
I'm trying to format sting to Date() and format Date to String in order to set value to date_announce label. Can anyone help me please?
If you break down what you are trying to do, there are actually 2 steps that require two different date formatters.
Convert an input date string (e.g. "2021-05-23T06:35:47.409Z") to a Date
Convert the Date to an output string in a different format.
Try this code instead:
var str = "2021-05-23T06:35:47.409Z"
//Set up a DateFormatter for input dates in "Internet" date format"
var inputFormatter = DateFormatter()
inputFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSZ"
//Set up an output date formatter (in the local time zone)
var outputFormatter = DateFormatter()
outputFormatter.dateFormat = "MMM d yyyy, h:mm:ss a"
if let formattedtoDate = inputFormatter.date(from: str) {
let formattedtoString = outputFormatter.string(from: formattedtoDate)
print("'\(str)' = '\(formattedtoString)'")
} else {
print("Can't convert the string \(str) to a Date")
}
Edit:
(As Leo Dabus pointed out in a comment, you usually should not use a fixed dateFormat string in a DateFormatter that generates user-visible date strings. Better to use date and time styles and let the DateFormattter pick a specific format appropriate to the user's locale and language.)

Date format from url (JSON)

How would I be able to take the date format from a URL and turn It into 2 separate date values in SwiftUI. The format from JSON is 2019-11-06 18:30:00 and I'm trying to get it to show as Dec 5 and would also like it to separate the time and show 8:00PM, is this possible?
This is the code that references the start time:
let startTime: String
var startTime: String {
return self.post.startTime
}
Let's step around the fact that 2019-11-06 18:30:00 can't be represented as Dec 5 and 8:00PM and focus on the work flow you'd need.
The basic idea is to:
Convert the String to a Date, via a DateFormatter
Use a custom DateFormatter to format the Date to the required "date" value
Use a custom DateFormatter to format the Date to the required "time" value
This might look something like...
let startTime = "2019-11-06 18:30:00"
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
if let date = formatter.date(from: startTime) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM d"
let dateString = dateFormatter.string(from: date)
let timeFormatter = DateFormatter()
timeFormatter.dateFormat = "h:ma"
let timeString = timeFormatter.string(from: date)
} else {
print("Bad date/format")
}
In my testing, this outputs Nov 6 and 6:30PM
you can pass your string date to date with this function
func stringToDate(date: String, format: String) -> Date
{
let date2 = date.count == 0 ? getCurrentDate(format: "dd-MM-yyyy") : date
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone.init(identifier: "América/Mexico_City")
dateFormatter.dateFormat = format
let dateDate = dateFormatter.date(from: date2)
return dateDate!
}
func getCurrentDate(format: String) -> String
{
let formD = DateFormatter()
formD.dateFormat = format
let str = formD.string(from:Date())
return str
}
let dateA = stringToDate(date: "2019-11-06 18:30:00", format: "yyyy-MM-dd HH:mm:ss")
if dateA < Date() //Date() always will be the current date, including the time
{
print("dateA is older")
}
else
{
print("dateA in newer")
}
play with the format examples formats

dateformat spelling format swift

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

How to convert a String to NSdate?

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/