Date not coming correctly after formate in swift - swift

I have separated date and time according to my code, then I have used DateFormatter but date not coming correctly.. why?
coming like this: Optional("08/15/0020")
var formateFromdate: String?
var formateTodate: String?
func addDate(){
var fromDateArr = fromDateLabel.text!.components(separatedBy: ",")
fromDate = fromDateArr[0]
fromTime = fromDateArr[1].replacingOccurrences(of: " ", with: "")
var toDateArr = toDateLabel.text!.components(separatedBy: ",")
toDate = toDateArr[0]
toTime = toDateArr[1].replacingOccurrences(of: " ", with: "")
let inputFormatter = DateFormatter()
inputFormatter.dateFormat = "MM/dd/yyyy"
let showDateFrom = inputFormatter.date(from: fromDate)
inputFormatter.dateFormat = "MM/dd/yyyy"
formateFromdate = inputFormatter.string(from: showDateFrom!)
print(formateFromdate)
}
note: here fromDate = 08/15/2020 coming correct but after formate date not coming correct
OutPut:
Optional("08/15/0020") it should be 08/15/2020

From the formatted date output, it seems the value of fromDate = fromDateArr[0] is "08/15/20" If that's the case, you will have to use a date format as below;
let inputFormatter = DateFormatter()
inputFormatter.dateFormat = "MM/dd/yy"
let showDateFrom = inputFormatter.date(from: fromDate)
inputFormatter.dateFormat = "MM/dd/yyyy"
let formateFromdate = inputFormatter.string(from: showDateFrom!)
print(formateFromdate)

You need to unwrap it first
if let formate = inputFormatter.string(from: showDateFrom!){
print(formate)
}

Related

Does dateFromServer return the current Timezone of the person?

When I am running the code below the date and time returned are in correct format but just not from what's coming from the API which in this case is the currentVehicle.LastCommunicationDate!
Instead of coming the time from the currentVehicle.LastCommunicationDate! it's just returning a random timezone I think that is getting from the Server or something like that.
The output of the code I have right now is: 2022-01-21 02:04:15 when it should have been the live time in my local timezone but it's getting a different timezone.
The LastCommunicationDate coming from postman is in json format: "LastCommunicationDate": "2022-01-21T10:58:21.367",
The time i want to be is the one from Postman just converted from json to normal time like: yyyy-MM-dd HH:mm:ss
let timeinterval : TimeInterval = (currentVechicle.LastCommunicationDate! as NSString).doubleValue
let dateFromServer = NSDate(timeIntervalSinceNow:timeinterval)
let outFormatter = DateFormatter()
outFormatter.locale = Locale(identifier: "en_Al")
print(dateFromServer)
let dateFormater = outFormatter
outFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
print(dateFormater.string(from: dateFromServer as Date))
let dateFromServers = dateFormater.string(from: dateFromServer as Date)
LastCommunicationDate is a string, but you are converting it to a Double. Try this instead:
let lastCommunicationDate = "2022-01-21T10:58:21.367"
//Create dateformatter to convert string to Date
let isoDateFormatter = ISO8601DateFormatter()
isoDateFormatter.formatOptions = [
.withFullDate,
.withTime,
.withColonSeparatorInTime,
.withFractionalSeconds
]
let isoDateFormatter2 = ISO8601DateFormatter()
isoDateFormatter2.formatOptions = [
.withFullDate,
.withTime,
.withColonSeparatorInTime
]
let date = isoDateFormatter.date(from: lastCommunicationDate) ?? isoDateFormatter2.date(from: lastCommunicationDate)
//Create dateformatter to format date for output
let outFormatter = DateFormatter()
outFormatter.locale = Locale(identifier: "en_Al")
outFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let dateFromServers = outFormatter.string(from: date!)

How to format dates without the '0' in the beginning with 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

Any way to sort custom object inside array?

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 })

Swift 3.0: Get the difference between server UTC time & Local time

I want to get the difference between server UTC time and Local time.
I write some code here..
var localTime:String!
var timeString:String = "06:05:00" //This is server UTC time
let dateFormator = DateFormatter()
dateFormator.dateFormat = "H:mm:ss"
dateFormator.timeZone = TimeZone(abbreviation: "UTC")
let dt = dateFormator.date(from: timeString)
if dt != nil {
dateFormator.timeZone = TimeZone.current
dateFormator.dateFormat = "h:mm a"
localTime = dateFormator.string(from: dt!) //Converted current local time
}
let date = Date()
let dateFormatter2 = DateFormatter()
dateFormatter2.dateFormat = "h:mm a"
let timeStr = dateFormatter2.string(from: date)// Current time
let date1 = dt!
let date2 = dateFormatter2.date(from: timeStr)!
var _date1:String = localTime
var _date2:String = timeStr
//TODO: Remove the bellow two line and Comment *Line: 1 , Uncomment *Line: 2
//_date1 = "11:00"
//_date2 = "12:00"
let _dateFormatter = DateFormatter()
_dateFormatter.dateFormat = "HH:mm a" //*Line: 1
//_dateFormatter.dateFormat = "HH:mm" //*Line: 2
let date3 = _dateFormatter.date(from: _date1)
let date4 = _dateFormatter.date(from: _date2)
let _interval = date4!.timeIntervalSince(date3!)
let intervalInInt = Int(_interval)
let minutes3 = Int((_interval / 60).truncatingRemainder(dividingBy: 60))
let hours3 = Int((_interval / 3600))
String(format: "%02d:%02d", hours3, minutes3)
In this code time interval chunk of code works fine when time is in HH:mm formate, But I would like to check difference between "11:00 AM" & "1:00 PM" so it's fails. So please help me. Thanks in advance.
Use following to difference with local timestamp
let date = Date()
let timeZoneOffset = Double(TimeZone.current.secondsFromGMT(for: date))

Comparing Time Strings

I have 2 times that create a time range that a map annotation is visible(a start time and an end time). Whenever the current time is greater than the end time, the annotation is removed. The user inputs the times as a string then I add that time string to the current date string, then I convert the date as "h:mm a, M/dd/yyyy" into an actual date. The problem I am having is that if someone says the event starts at night (PM) then ends in the early morning or something (AM) then the event annotation is instantly removed because it creates the end time as AM time of the day that is about to end instead of the new day. Here is my current method for getting the time strings in code:
let SpotStartTime = StartTimeTextField.text;
let SpotEndTime = EndTimeTextField.text;
let date = NSDate();
let formatter = NSDateFormatter();
formatter.dateFormat = "M/dd/yyyy";
let Date = formatter.stringFromDate(date)
let EndTime = SpotEndTime;
let RealEndTime = (EndTime! + ", " + Date);
print(RealEndTime);
then I convert this string into a date using this method:
let TimeStr = EndTime
let dateFormater : NSDateFormatter = NSDateFormatter()
dateFormater.dateFormat = "h:mm a, M/dd/yyyy
let EndDate = (dateFormater.dateFromString(TimeStr))
let realEnd = EndDate
How do I modify this so that I can compare the StartTimeTextField to the EndTimeTextField? I need something that basically compares the two and if the StartTimeTextField has "PM" in it and the EndTimeTextField has "AM" in it then the EndTime gets 24 hours added to it, but I don't know how to do this in code.
Can anyone help? Thanks
I hope that I understood what you want to do, I come up with this function:
func getTime(startTime:String, startM:String, endTiem: String, endM:String) {
let date = NSDate();
let formatter = NSDateFormatter();
formatter.dateFormat = "M/dd/yyyy";
let dateStrStart = formatter.stringFromDate(date)
var dateStrEnd = ""
if (startM == "PM" && endM == "AM") {
let dateEnd = NSDate(timeInterval: 86400, sinceDate: date)
let formatter = NSDateFormatter();
formatter.dateFormat = "M/dd/yyyy";
dateStrEnd = formatter.stringFromDate(dateEnd)
} else {
dateStrEnd = dateStrStart
}
let RealEndTime = (endTiem + ", " + dateStrEnd);
let RealStartTime = (startTime + ", " + dateStrStart);
}
you just have to grab the AM or PM part.
And if the startTime is PM and the endTime is AM then your dateEnd is the currentDate plus one day.