How to change day of week from English to Locale - swift

I'm working on calendar with this pod https://github.com/miraan/CalendarDateRangePickerViewController. I changed months names but can't change days of week.
I tried to add components.calendar?.locale = Locale(identifier: "ru_RU") and dateFormatter.locale = Locale.autoupdatingCurrent but nothing has changed.
func getWeekdayLabel(weekday: Int) -> String {
var components = DateComponents()
components.calendar = Calendar.current
components.calendar?.locale = Locale(identifier: "ru_RU")
components.weekday = weekday
let date = Calendar.current.nextDate(after: Date(), matching: components, matchingPolicy: Calendar.MatchingPolicy.strict)
if date == nil {
return "E"
}
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEEEE"
return dateFormatter.string(from: date!)
}

Your code is needlessly overcomplicated.
What you want to get is just weekday symbols. Shortest form as possible.
And Calendar has dedicated property for this: veryShortStandaloneWeekdaySymbols.
And the result function is:
func getWeekdayLabel(weekday: Int) -> String {
// TODO: Move this away, and reuse, it would be the same for every call ↓
var calendar = Calendar.autoupdatingCurrent
calendar.locale = Locale(identifier: "ru_RU") // Or any other locale, if you wan current, just drop this line
// TODO: ↑
return calendar.veryShortStandaloneWeekdaySymbols[weekday - 1] // because CalendarDateRangePickerViewController uses 1...7 weekday range, and here it's 0...6(or 0..<7)
}
And if you want weekdays described in more length use other *weekdaySymbols from the See Also section.

Related

How can I show month and year in 12's timezone in swift?

func getMonYearDateFormat() -> String {
let dateFormatter = DateFormatter()//EEEE, d, MMM
dateFormatter.dateFormat = is24Hour() ? "yyyy-MM-dd' 'HH:mm:ss" : "yyyy-MM-dd' 'h:mm:ss a"
dateFormatter.timeZone = TimeZone.current
dateFormatter.locale = Locale.current
guard let oldDate = dateFormatter.date(from: self) else { return "" }
let convertDateFormatter = DateFormatter()
convertDateFormatter.dateFormat = "MMMM yyyy"
return convertDateFormatter.string(from: oldDate)
}
I show month and year as title in table view. I wrote this function to convert the date of the relevant card to month and year. If the device is in the 24-hour time zone, the function works properly. However, if the device is in the 12th time zone, it returns blank and I cannot see the month and year of the relevant card. I couldn't find the part that I wrote incorrectly in the function.
I've tested your code with 12 hour format and it works. The only thing I've. change is to use the 12 hour format without call is24Hour() because you did not provide that code. So I suspect the point of failure is the is24Hour() function.
As mentioned in the comments I would recommend you to investigate how you get this string and if possibly use the original Date object instead if it exists but below is a solution that I think handles the 12 vs 24h issue in an efficient way.
The logic is to first convert using 24h and if that returns nil then convert using the 12h format.
I have declared all formatters I use as static properties so they only get created one since creating a DateFormatter is expensive
extension String {
private static let formatter24: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd' 'HH:mm:ss"
return dateFormatter
}()
private static let formatter12: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd' 'h:mm:ss a"
return dateFormatter
}()
private static let formatterMonthYear: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM yyyy"
return dateFormatter
}()
func getMonYearDateFormat() -> String {
let date = Self.formatter24.date(from: self) ?? Self.formatter12.date(from: self)
guard let date else { return "" }
return Self.formatterMonthYear.string(from: date)
}
}

How do I return the correct day of the week using dateFormatter in Swift 4?

The following Swift 4 code returns the incorrect day of the week for some cities.
// should be "Thu" but returns "Wed" for Aleppo for example
// current location set to Cupertino
// US Cities are correct
let date = "2021-04-29T07:00:00+03:00" // Aleppo
//let date = "2021-04-29T07:00:00-07:00" // Cupertino
let day = self.getDayName(stringDate: date)
print(day)
func getDayName(stringDate: String) -> String
{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let date = dateFormatter.date(from: stringDate)!
dateFormatter.dateFormat = "E"
let day = dateFormatter.string(from: date)
return day
}
Any ideas on how to fix this? Thanks

Compare current system date with another date(which is coming as string format 2019-11-22) in swift

I'm getting date as a sting format from API (2019-11-22), I want to compare this date with current date.
I tried converting current date as string format this is success but this is not satisfying requiremet. I have to convert to String(2019-11-22) to Date and then I can compare two dates.
How can I convert string (2019-11-22) to Date to compare with system date pls help I'm lead knowledge in dates. Thanks in advance.
extension Date {
static func getCurrentDate() -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
return dateFormatter.string(from: Date())
}
}
if Date() < apiEach["ExpiryDate"]! as! Date{
//apiEach["ExpiryDate"]! is 2019-11-22
pritn("You can proceed it's not outdated")
}
apiEach["ExpiryDate"] is a string (apiEach["ExpiryDate"] as! Date will crash) so you have two options:
Convert the current date to string
if Date.getCurrentDate() < apiEach["ExpiryDate"] as! String { ...
Convert the API string to Date and compare that
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd"
if let apiDate = dateFormatter.date(from: apiEach["ExpiryDate"] as! String),
Date() < apiDate { ...
func minimumDate(result:String) -> Bool {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let myDate = dateFormatter.date(from: "\(result)")
dateFormatter.dateFormat = "yyyy-MM-dd"
let now = Date()
let startDateComparisionResult:ComparisonResult = now.compare(myDate!)
if startDateComparisionResult == ComparisonResult.orderedAscending {
print("Current date is smaller than end date.")
let somedateString = dateFormatter.string(from: myDate!)
print(somedateString)
return true
}
else if startDateComparisionResult == ComparisonResult.orderedDescending {
// Current date is greater than end date.
print("Current date is greater than end date.")
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let date1String = dateFormatter.string(from: myDate!)
let date2String = dateFormatter.string(from: now)
if date1String == date2String {
print("Equal date")
return true
}
return false
}
else if startDateComparisionResult == ComparisonResult.orderedSame {
// Current date and end date are same
print("Current date and end date are same")
return true
}
return true
}
Since the date format "yyyy-MM-dd" can be properly sorted/compared you can either convert current date to a string and compare it with your API value
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let now = dateFormatter.string(from: Date())
switch now.compare(input) { //input is from API
case .orderedSame:
print("Same")
case .orderedAscending:
print("Before")
case .orderedDescending:
print("After")
}
If you want to compare dates it is important that Date() will also include the current time while a date converted using a date formatter with a date only format will have its time zeroed out (midnight) so the comparison might not be correct if the date part is the same. To handle this it is better to use DateComponents
let calendar = Calendar.current
guard let date = dateFormatter.date(from: input) else { return //or error }
let components = calendar.dateComponents([.year, .month, .day], from: now, to: date)
if let year = components.year, let month = components.month, let day = components.day {
switch (year + month + day) {
case 0: // all values are zero
print("Same")
case ..<0 : // values will be zero or negative so sum is negative
print("After")
default: // values will be zero or positive so sum is positive
print("Before")
}
}

Problem converting a string to a Date Object

I have a DatePicker View, When the user clicks a UITextField, it show the DatePicker, which the user can of course, pick a date.
The problem is, when I'm trying to convert the String, to be a date object, I get nothing, so I cannot compare two dates for example.
func checkDate(){
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: Locale.current.identifier)
dateFormatter.timeZone = .current
dateFormatter.dateFormat = "dd/MM/yy"
guard let startDate = mView.startDateTextField.text else { return }
print("DATE: \(startDate)")
guard let startDateFromString = dateFormatter.date(from: startDate) else { return } //I think it returns here.
//Won't get here.
print("DATE: \(startDate)")
guard let endDate = mView.endDateTextField.text else { return }
guard let endDateFromString = dateFormatter.date(from: endDate) else { return }
if startDateFromString.compare(endDateFromString) == ComparisonResult.orderedDescending{
print("Start date cannot be greater than end date.")
}
}
I tried to debug, and the break point does gets to startDateFromString line, but from theres "jumps" outside, so I guess it won't get the Date from the string and returns.
I just can't figure out why.
EDIT: This is where I set the TextField Text to be the date chosen from the DatePicker.
#objc func datePickerValueChanged(sender: UIDatePicker){
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
dateTextField.text = dateFormatter.string(from: sender.date)
}
Maybe you are using wrong dateFormat. Check your dateFormat from here
For example if your dateString is "Mar 1, 2019", you have to use it as dateFormat "MMM d, yyyy"
dateFormatter.dateFormat = "MMM d, yyyy"

To use the conditional branch (If statements) to obtain the time

We want to assign the result Once at 23:00 to number 1, but does not move the following source.
Perhaps, I think not been able conversion of type String.
I want you to tell me the solution
import UIKit
let now = NSDate() // gettime
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: "ja_JP")
dateFormatter.dateFormat = "hh" // o`clock
print(dateFormatter.stringFromDate(now)) // convert to String
if now = 23 {
number1 = result
result = 0
}
let now = NSDate() // gettime
let calendar = NSCalendar.autoupdatingCurrentCalendar()
// If you want to know the hour in a particular time zone, set it here.
// For example, to get the time in Japan:
// calendar.timeZone = NSTimeZone(name: "Asia/Tokyo")!
// By default, the calendar uses the system time zone setting.
let hour = calendar.component(NSCalendarUnit.Hour, fromDate: now)
if hour == 23 {
print("It is the appointed hour.")
}