Weekday symbol in MO TU WE ... format? - ios

I need weekday symbol in MO TU WE TH FR SA SU
I am using setDateFormat:#"EEEEE"]; with shortWeekdaySymbols
But it only return Sun Mon etc. Let me know if it is possible ?

According to the Unicode specification you should be able to use the EEEEEE (six E) format to get a two-letter weekday symbol.

As rmaddy has mentioned, you can use six E format. That will give you Mo, Tu, We etc. But if you want them in captitals specifically (MO, TU, WE, etc), you can set the veryShortWeekdaySymbols property of the NSDateFormatter object and use the same format mentioned in the question. You can use any Weekday Symbol you wish. As follows:
NSDate *date = [NSDate date];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.veryShortWeekdaySymbols = #[#"SU", #"MO", #"TU", #"WE", #"TH", #"FR", #"SA"];
formatter.dateFormat = #"EEEEE";
NSLog(#"%#", [formatter stringFromDate:date]);

Related

NSDateFormatter doesn't support long-form day periods ('b' or 'B')

NSDateFormatter doesn't seem able to use the 'B' or 'b' format specifiers. 'B' is a little like 'a' (am/pm), but it outputs things like "at night" or "in the morning".
For example, this code:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSLocale* locale = [[NSLocale alloc] initWithLocaleIdentifier:#"en-US"];
NSString *dateTemplate = [NSDateFormatter dateFormatFromTemplate:#"h:mmB"
options:0
locale:locale];
[dateFormatter setDateFormat:dateTemplate];
[dateFormatter setLocale:locale];
NSString* now = [dateFormatter stringFromDate:[NSDate date]];
NSLog(#"String:\t%#\ndateTemplate:\t%#",
now,
dateFormatter.dateFormat);
...prints this:
String: 10:23 PM // Should be "10:23 at night"
dateTemplate: h:mm a // Note that 'B' turned into 'a' (am/pm)
Skipping dateFormatFromTemplate and putting the format directly into the formatter has the same effect.
The docs say that iOS 7 and later use tr35-31. It's unclear whether that spec supports 'B'. The formatting table for version 31 mentions 'a', but does not mention 'B'. On the other hand, the spec for all of tr35 does indeed mention 'B'.
If you download the actual CLDR data for version 31, you can find dayPeriod entries for "in the evening" etc.
The data exists; is there another formatting string I can use to get longer "day period" strings?
You are correct that B is used for a "natural language" description of the day period. However, the problem you're experiencing is arising from using it in a date format template.
It would seem that the CLDR does not recognize that it should keep B in a date format string when you ask it to localize a template format. Thus, it's substituting a back in to the final format string.
Incidentally, if you run through +[NSLocale availableLocaleIdentifiers], you'll see that there isn't any locale that support B in a template string.
However, if you use B in a date format string directly, then it works as expected:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"h:mm B";
NSLog(#"%#", [dateFormatter stringFromDate:[NSDate date]]);
Outputs:
12:57 in the afternoon
I'm able to get it to work in a iOS playground in Xcode 9. Sorry, the code below is in Swift, but it does seem to be working for me.
let loc = Locale(identifier: "en-US")
let testDF = DateFormatter()
testDF.dateFormat = "MM-dd-yyyy HH:mm"
testDF.locale = loc
let df = DateFormatter()
df.dateFormat = "h:mm B"
df.locale = loc
df.string(from: testDF.date(from: "09-21-2018 17:22")!) // "5:22 in the afternoon"
df.string(from: testDF.date(from: "09-21-2018 19:22")!) // "7:22 in the evening"
df.string(from: testDF.date(from: "09-21-2018 22:22")!) // "10:22 at night"
df.dateFormat // "h:mm B"

Why [dateFormatter stringFormat:[NSDate date]] can not be converted to a number

//In NSDate category:
+ (NSString *)timeWithFormat:(NSString *)format {
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = format;
return [formatter stringFromDate:[NSDate date]];
}
//Swift3.0 invoke method:
let nowHour: Int = Int(NSDate.time(withFormat: "HH"))!//Crash code,I can not be reproduced
I think when calling [formatter stringFromDate:[NSDate date]] the [NSDate date] code may be the return value is nil. Is this likely to happen? If so, how to reproduce it ? NSDate date return nil question
Device info:
From looking at your code I think this is a locale issue. Not all locales use 0-9 to represent time.
If I run your code over all the 740 locale identifiers that's available for me, it fails on 60 of them. A subset of the locale identifiers where this code fails is presented below, along with their (American) English name and the string they produce for with the format "HH" for 2 PM:
ar Arabic ١٤
ars Najdi Arabic ١٤
as Assamese ১৪
bn Bengali ১৪
ckb Central Kurdish ١٤
dz Dzongkha ༡༤
fa Persian ۱۴
hi Hindi १४
ks Kashmiri ۱۴
lrc Northern Luri ۱۴
mr Marathi १४
my Burmese ၁၄
mzn Mazanderani ۱۴
ne Nepali १४
pa_Arab Punjabi (Arabic) ۱۴
ps Pashto ۱۴
ur_IN Urdu (India) ۱۴
uz_Arab Uzbek (Arabic) ۱۴
Trying to create a number from these string like Int("१४")! will crash, because the Int constructor returns nil which is then being force unwrapped (!).
If you're interested in getting a numerical value for the hour of a given time, I would recommend that you get the hour date component using an appropriate calendar. For example:
Calendar.current.component(.hour, from: date)

Convert NSString to NSDate

I wanted to convet the string to date.
Date in string format is: 2016-09-12T09:52:39Z (Without any space)
Most of the solutions which I found has atleast space in between date and time text. Which is not working in my case.
The major issue in converting above date format is that "T" and "Z". I think some how the date formatter is not distingushing date "dd" and timezone "T". I did attempted to format that but its not working.
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss'Z'"];
NSDate *date = [[NSDate alloc] init];
date = [formatter dateFromString:datestring];
Any solution to convert such string into date?
Edit: I had mention while posting question is that - In most of question related to "converting string to date" has spaces in bettwen those text, So, You can write formatter according to that. In my case, There was no space between date and hour part & instead it has T. Hence, I was not able to convert the string date into date object, Instead I was getting null. For which I tried some solutions & after that I posted the question.
plz check your datestring. it's working fine in my end.

Converting NSString into NSDAte once again

i have a label which is :
_labelCell.text = [2014-06-22 20:27:48 +0000];
What i want to do is to convert this string into NSDate so i can format it into something like : EEEE dd MM yyyy
i try :
// convert to date
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"YYYY-MM-dd'T'HH:mm:ss'+0000'"];
NSDate *dte = [dateFormat dateFromString:str];
NSLog(#"Date: %#", dte);
but it always give me a NULL NSDate
Can someone help me on this little thing ?
Thank you very much.
Your date format needs to resemble the format of the date. See http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns for the format patterns. For your date 2014-06-22 20:27:48 +0000 you need to use "yyyy-MM-dd HH:mm:ss ZZZ". Note that it must be "yyyy", not "YYYY", and the zone field should be parsed rather than treated as a literal. There is no "T" separating date and time.
Your date formatter is expecting a T in between the date and time. It returns null because there the string has a space instead of a T.
You're also missing a space before the timezone.
Fix those two issues, and it should work:
dateFormat.dateFormat = #"YYYY-MM-dd HH:mm:ss '+0000'";
Beware this might give you the wrong date, because of time zone issues. Test that out, and if it doesn't work adjust accordingly with dateFormat.timeZone = ...

NSDateFormatter: Date according to currentLocale, without Year

This can't be too difficult..
I want to display a date without the year. For example: "Aug, 2nd" (USA) or "02.08." (GERMANY)
It must work for a bunch of other locales as well.
My only idea so far is to do a normal format with year, and then remove the year-portion from the generated string.
I think you need to take a look at:
+ (NSString *)dateFormatFromTemplate:(NSString *)template options:(NSUInteger)opts locale:(NSLocale *)locale
As per the docs:
Returns a localized date format string representing the given date format components arranged appropriately for the specified locale.
Return Value
A localized date format string representing the date format components given in template, arranged appropriately for the locale specified by locale.
The returned string may not contain exactly those components given in template, but may—for example—have locale-specific adjustments applied.
Discussion
Different locales have different conventions for the ordering of date components. You use this method to get an appropriate format string for a given set of components for a specified locale (typically you use the current locale—see currentLocale).
The following example shows the difference between the date formats for British and American English:
NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US"];
NSLocale *gbLocale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_GB"];
NSString *dateFormat;
// NOTE!!! I removed the 'y' from the example
NSString *dateComponents = #"MMMMd"; //#"yMMMMd";
dateFormat = [NSDateFormatter dateFormatFromTemplate:dateComponents options:0 locale:usLocale];
NSLog(#"Date format for %#: %#",
[usLocale displayNameForKey:NSLocaleIdentifier value:[usLocale localeIdentifier]], dateFormat);
dateFormat = [NSDateFormatter dateFormatFromTemplate:dateComponents options:0 locale:gbLocale];
NSLog(#"Date format for %#: %#",
[gbLocale displayNameForKey:NSLocaleIdentifier value:[gbLocale localeIdentifier]], dateFormat);
// Output:
// Date format for English (United States): MMMM d, y
// Date format for English (United Kingdom): d MMMM y
Extra code (add this to the code above):
//
NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
formatter.locale = gbLocale;
formatter.dateFormat = dateFormat;
NSLog(#"date: %#", [formatter stringFromDate: [NSDate date]]);
See here:
NSDateFormatter Class Reference
The two examples you give are very different from each other. One uses the abbreviated month name while the other uses the 2-digit month number. One uses a day ordinal ("2nd") while the other simply uses the 2-digit day number.
If you can accept using the same general format for all locales then make use of NSDateFormatter dateFormatFromTemplate:options:locale:.
NSString *localFormat = [NSDateFormatter dateFormatFromTemplate:#"MMM dd" options:0 locale:[NSLocale currentLocale]];
The result of this call will give back a format string you can use with NSDateFormatter setDateFormat:. The order of the month and day will be appropriate for the locale as well as any additional punctuation that should be added.
But again, this won't solve your exact needs because of the completely different formats you appear to want for each locale.
Swift 3
let template = "EEEEdMMM"
let locale = NSLocale.current // the device current locale
let format = DateFormatter.dateFormat(fromTemplate: template, options: 0, locale: locale)
let formatter = DateFormatter()
formatter.dateFormat = format
let now = Date()
let whatYouWant = formatter.string(from: now) // Sunday, Mar 5
Play with template to match your needs.
Doc and examples here to help you determine the template you want.
All the above answers are using an older api released in iOS 4. A newer api that was introduced in iOS 8 is available.
In the apple documentation for DateFormatter it provides the below sample code for only showing the day and month in a date. You can just pass the Locale.current to the DateFormatter if you don't want to specify a specific locale (I haven't been able to find out if this is the default implementation so would advise that you always set locale before using setLocalizedDateFormatFromTemplate(_:) which is suggested in the docs).
let dateFormatter = DateFormatter()
let date = Date(timeIntervalSinceReferenceDate: 410220000)
// US English Locale (en_US)
dateFormatter.locale = Locale(identifier: "en_US")
dateFormatter.setLocalizedDateFormatFromTemplate("MMMMd") // set template after setting locale
print(dateFormatter.string(from: date)) // December 31
// British English Locale (en_GB)
dateFormatter.locale = Locale(identifier: "en_GB")
dateFormatter.setLocalizedDateFormatFromTemplate("MMMMd") // // set template after setting locale
print(dateFormatter.string(from: date)) // 31 December

Resources