How to extract day, month and year (dd-MM-yyyy) from Date (2018-09-28 09:42:00 +0000 ) without time in Date format - iOS swift? - ios

I want to get 2018-09-28 from 2018-09-28 09:42:00 +0000 in Date format. I
can extract the same in string format but I want to get this in Date format. Here is my sample code.
let date = Date(timeIntervalSince1970: (TimeInterval(timer/1000)))
let df = DateFormatter()
df.dateFormat = "yyyy-MM-dd"
let myDate = df.string(from: date)
let updateDate = df.date(from: myDate)
//date - 2018-09-28
//updateDate - 2018-09-28 09:42:00 +0000

You can simply get your date string prefix 11 and insert noon time when parsing your string:
let str = "2018-09-28 09:42:00 +0000"
let df = DateFormatter()
df.locale = Locale(identifier: "en_US_POSIX")
df.dateFormat = "yyyy-MM-dd HH:mm"
if let date = df.date(from: str.prefix(11) + "12:00") {
print(date.description(with: .current))
}
// Friday, September 28, 2018 at 12:00:00 PM Brasilia Standard Time

Related

Get only time from Date

How to get only time from the date with am/pm. Below is my code what I have tried so far:
func changeFormat(str:String) -> String {
let dateFormatter = DateFormatter()
let newDateFormatter = DateFormatter()
// step 1
dateFormatter.dateFormat = "MM/dd/yyyy HH:mm aa" // input format
newDateFormatter.dateFormat = "HH:mm aa" // output format
let date = dateFormatter.date(from: str)!
// step 2
let string = newDateFormatter.string(from: date)
return string
}
Usage:
let strTimeFromDate = changeFormat(str: self.response?.Data[indexPath.row].ADateTime ?? "")
input date:
06/22/2021 2:00 PM
output:
12:45 PM
Getting wrong time return after formatting. Please guide what's wrong with above code
As mentioned by #JoakimDanielson in the comment, you are mixing HH (24 hours format) with hh (12 hours format). Using hh for the dateFormatter (given your input has 02:00 PM) should fix your issue (as long as this input value was captured in the same time zone in which you intend to convert).
In case you are still seeing that the output is not expected, then it is the issue with missing timeZone info in your input. You are trying to convert String > Date > String without specifying an input timeZone & output timeZone. You can try printing these values in your implementation.
print("dateFormatter.timeZone.secondsFromGMT() : \(dateFormatter.timeZone.secondsFromGMT())")
let date = dateFormatter.date(from: str)!
print("parsed date : \(date)")
print("\n ------------------------ \n")
// step 2
print("newDateFormatter.timeZone.secondsFromGMT() : \(newDateFormatter.timeZone.secondsFromGMT())")
let string = newDateFormatter.string(from: date)
print("parsed string : \(string)")
For me it prints following. 19800 / (60 * 60) = 5.5 (+05:30)
dateFormatter.timeZone.secondsFromGMT() : 19800
parsed date : 2021-06-22 06:30:00 +0000
------------------------
newDateFormatter.timeZone.secondsFromGMT() : 19800
parsed string : 12:00 PM
The issue is - for these two conversions to happen correctly - you must specify an appropriate time zone.
String to Date
Date to String
Here's what that implementation could look like. Assuming input is "06/22/2021 2:00 PM +0530"
func changeFormat(str: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(secondsFromGMT: Int(5.5*60*60)) // +05:30
let newDateFormatter = DateFormatter()
newDateFormatter.timeZone = TimeZone(secondsFromGMT: Int(5.5*60*60)) // +05:30
dateFormatter.dateFormat = "MM/dd/yyyy hh:mm aa Z"
newDateFormatter.dateFormat = "hh:mm aa"
let date = dateFormatter.date(from: str)!
let string = newDateFormatter.string(from: date)
return string
}
When you are consuming this date string from your backend server, you should consider using appropriate time zone for it. An example, assuming input is "06/22/2021 2:00 PM +0000" -
func changeFormat(str: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0) // Server timeZone (UTC)
let newDateFormatter = DateFormatter()
newDateFormatter.timeZone = TimeZone.current // User's timeZone
dateFormatter.dateFormat = "MM/dd/yyyy hh:mm aa Z"
newDateFormatter.dateFormat = "hh:mm aa"
let date = dateFormatter.date(from: str)!
let string = newDateFormatter.string(from: date)
return string
}
"HH" is for 24h format and "aa" is for 12h format so you can't mix them, so you should use "hh:mm a" instead for both DateTimeFormatter's

Date Time change when convert to string issue

I'm trying to subtract minute from my date. BaseDate is my date and dateMinusMin is subtract is minuteFrom my date which work completely fine.
let baseDate = "2020-03-06 06:00" //My date With format "yyyy-MM-dd HH:mm"
let dateMinusMin = Calendar.current.date(byAdding: .minute, value: -(240), to: baseDate)!
print(dateMinus4Hours) \\2020-03-06 02:00:00 +0000
But when I convert Date to string time is change dramatically and showing 07:30 instead of 02:00.
let modifyStr = Utill.getLocalStringFromDate("yyyy-MM-dd HH:mm Z", date: dateMinus4Hours, iden: "en_US_POSIX")
print(modifyStr) \\ 2020-03-06 07:30 +0530
OutPut = 2020-03-06 07:30 +0530
Function to convert Date To string
func getLocalStringFromDate(_ currentFormat:String,date:Date,iden:String) -> String {
let formatter = DateFormatter()
formatter.dateFormat = currentFormat
formatter.locale = Locale(identifier: iden)
return formatter.string(from: date)
}
I don't find any issue in your code. you can see result in below image.
Given Input - 06:00 hours
Output - 02:00 hours (4 hours minus as you want)

How to convert string to date correctly? [duplicate]

This question already has answers here:
NSDateFormatter still parsing instead having incorrect format
(3 answers)
Closed 3 years ago.
Why does dateFormatter return the correct date from an invalid format string?
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let date = dateFormatter.date(from: "2020/////07////////10") //"Jul 10, 2020 at 12:00 AM"
I will say more - it also works unexpectedly
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let dotDate = dateFormatter.date(from: "2020....07...10") // Optional(2020-07-09 21:00:00 +0000)
let commaDate = dateFormatter.date(from: "2020,,,,07,,,,10") // Optional(2020-07-09 21:00:00 +0000)
My version is probably the issue in internal implementation on Apple side and comparison with the ASCII code table, where the codes of these characters (,,-,.,/) are in order (from 44 to 47)
This is probably a part of their algorithm.
If you want the formatter to return nil in this case you can change the dateFormat to:
dateFormatter.dateFormat = "yyyy/MM/dd"
Results
let date = dateFormatter.date(from: "2020/////07////////10") // nil
let date2 = dateFormatter.date(from: "2020/07/10") // Jul 10, 2020 at 12:00 AM"
let date3 = dateFormatter.date(from: "2020.07.10") // Jul 10, 2020 at 12:00 AM"
I did run your code and it gives nil
Whereas if I enter correct date format then I receive the output
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let date = dateFormatter.date(from: "2020-7-10")
print(date) // Optional(2020-07-10 00:00:00 +0000)

How to get the day of the week from a date in Swift

I can print the date in this format: Mon, Mar 19, 2018, but I am not sure how to get the Day of the week in this format.
Please help
let dateFormatter = DateFormatter()
// uncomment to enforce the US locale
// dateFormatter.locale = Locale(identifier: "en-US")
dateFormatter.setLocalizedDateFormatFromTemplate("EEE MMM d yyyy")
print(dateFormatter.string(from: Date())) // "Tue, Mar 20, 2018" for en-US locale
Note that I am using a template to provide the exact format, therefore the format will be properly localized in every language.
To get the day for a particular date:
let customDateFormatter = DateFormatter()
print(customDateFormatter.weekdaySymbols[Calendar.current.component(.weekday, from: Date())])
// "Wednesday"
source
Rather than needing to spell out a date format. I would simplify it further to:
dateFormatter.dateStyle = .full
Or if you just want the day:
dateFormatter.dateFormat = "EEEE"
With swift 4
func timeStamp()->String {
let dateFormater = DateFormatter()
dateFormater.locale = Locale(identifier: "en-US")
dateFormater.setLocalizedDateFormatFromTemplate("EEE MMM d yyyy")
return dateFormatter.string(from: Date())
}
Use it.
let getTimeStamp = timeStamp()
print(getTimeStamp)
dateFormatter.dateFormat = "EEE, MMM dd, yyyy"
For dat of week in alphabets, you use EEEE or EEE similar to MMM & yyyy for month year.
The best way to change your date is follow this method.
func ChangeDateFormat(date:String,FromFormat: String, ToFormat: String) -> String {
let dateFormatter1 = DateFormatter()
dateFormatter1.dateFormat = FromFormat
let myDate = dateFormatter1.date(from: date)
dateFormatter1.dateFormat = ToFormat
if(myDate != nil){
let Date = dateFormatter1.string(from: myDate!)
return Date
}
else{
return ""
}
}
and then you can use this method like
String(ChangeDateFormat(date: StartDate, FromFormat: "yyyy-MM-dd hh:mm:ss a", ToFormat: "MMM d, yyyy"))
You can pass your date format in which format do you want in your case it should be
String(ChangeDateFormat(date: StartDate, FromFormat: "Pass your date format", ToFormat: "EEE MMM d, yyyy"))

iOS Swift: how to convert specific date string format to Date object, when string contains time zone abbreviation?

I am getting a date string from server in the format of "March 08, 2018 16:00:00 PST" where there is a lot of whitespace between Month & Date.
My intention is to basically remove those extra whitespaces. My idea is that- I will convert the string into Date object, and then convert back to string.
How can I convert this into Date object using Date Formatter, taking timezone into consideration.
I am concerned about the "PST" here. While converting the Date to String, I will need in the format - "March 08, 2018 16:00:00 PST" i.e. PST (or whatever time zone comes in) should stay intact in the final string.
extension String {
func getDate(fromFormat format: String = "MMMM dd, yyyy HH:mm:ss zzz") -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
return dateFormatter.date(from: self)
}
}
let myDateString = "March 08, 2018 16:00:00 PST"
myDateString.getDate()
You can call with other time formats too.
Try this
let isoDate = "March 08, 2018 16:00:00 PST"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM dd, yyyy HH:mm:ss z"
let date = dateFormatter.date(from: isoDate)!
Try this
class func stringToDate (dateString:String, dateFormat:String) -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = dateFormat
let dateFromString = dateFormatter.date(from: dateString)
return dateFromString
}

Resources