NSDateFormatter setDateFormat에 대한 서수 월-일 접미사 옵션
NSDateFormatter의 어떤 setDateFormat 옵션을 사용하여 월-일의 서수 접미사를 가져 오나요?
예를 들어 아래 스 니펫은 현재 생성합니다.
8 월 15 일 토요일 오후 3:11
나는 얻기 위해 변경해야하는 것 :
오후 3시 11분 토요일 8월 15 일을
NSDate *date = [NSDate date];
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
[dateFormatter setDateFormat:@"h:mm a EEEE MMMM d"];
NSString *dateString = [dateFormatter stringFromDate:date];
NSLog(@"%@", dateString);
PHP에서는 위의 경우에 이것을 사용합니다.
<?php echo date('h:m A l F jS') ?>
PHP 형식화 문자열 의 S 옵션에 해당하는 NSDateFormatter가 있습니까?
이 답변 중 어느 것도 내가 사용하는 것만 큼 미적으로 만족스럽지 않았기 때문에 공유 할 것이라고 생각했습니다.
스위프트 3 :
func daySuffix(from date: Date) -> String {
let calendar = Calendar.current
let dayOfMonth = calendar.component(.day, from: date)
switch dayOfMonth {
case 1, 21, 31: return "st"
case 2, 22: return "nd"
case 3, 23: return "rd"
default: return "th"
}
}
목표 -C :
- (NSString *)daySuffixForDate:(NSDate *)date {
NSCalendar *calendar = [NSCalendar currentCalendar];
NSInteger dayOfMonth = [calendar component:NSCalendarUnitDay fromDate:date];
switch (dayOfMonth) {
case 1:
case 21:
case 31: return @"st";
case 2:
case 22: return @"nd";
case 3:
case 23: return @"rd";
default: return @"th";
}
}
분명히 이것은 영어로만 작동합니다.
NSDate *date = [NSDate date];
NSDateFormatter *prefixDateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[prefixDateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
[prefixDateFormatter setDateFormat:@"h:mm a EEEE MMMM d"];
NSString *prefixDateString = [prefixDateFormatter stringFromDate:date];
NSDateFormatter *monthDayFormatter = [[[NSDateFormatter alloc] init] autorelease];
[monthDayFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
[monthDayFormatter setDateFormat:@"d"];
int date_day = [[monthDayFormatter stringFromDate:date] intValue];
NSString *suffix_string = @"|st|nd|rd|th|th|th|th|th|th|th|th|th|th|th|th|th|th|th|th|th|st|nd|rd|th|th|th|th|th|th|th|st";
NSArray *suffixes = [suffix_string componentsSeparatedByString: @"|"];
NSString *suffix = [suffixes objectAtIndex:date_day];
NSString *dateString = [prefixDateString stringByAppendingString:suffix];
NSLog(@"%@", dateString);
이것은 iOS9부터 쉽게 수행 됩니다.
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterOrdinalStyle;
NSArray<NSNumber *> *numbers = @[@1, @2, @3, @4, @5];
for (NSNumber *number in numbers) {
NSLog(@"%@", [formatter stringFromNumber:number]);
}
// "1st", "2nd", "3rd", "4th", "5th"
스위프트 2.2 :
let numberFormatter = NSNumberFormatter()
numberFormatter.numberStyle = .OrdinalStyle
let numbers: [Int] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for number in numbers {
print(numberFormatter.stringFromNumber(number)!)
}
다음은 접미사를 생성하는 방법에 대한 또 다른 구현입니다. 생성되는 접미사는 영어로만 유효하며 다른 언어에서는 올바르지 않을 수 있습니다.
- (NSString *)suffixForDayInDate:(NSDate *)date
{
NSInteger day = [[[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] components:NSDayCalendarUnit fromDate:date] day];
if (day >= 11 && day <= 13) {
return @"th";
} else if (day % 10 == 1) {
return @"st";
} else if (day % 10 == 2) {
return @"nd";
} else if (day % 10 == 3) {
return @"rd";
} else {
return @"th";
}
}
Mac OS 10.5 및 iPhone의 날짜 포맷터 는 형식 지정자 표준으로 TR35 를 사용 합니다. 이 사양에서는 어떤 날짜에도 이러한 접미사를 허용하지 않습니다. 원하는 경우 직접 생성해야합니다.
이것은 재단에서 이미 구현되었습니다.
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .ordinal
numberFormatter.locale = Locale.current
numberFormatter.string(for: 1) //Should produce 1st
numberFormatter.string(for: 2) //Should produce 2nd
numberFormatter.string(for: 3) //Should produce 3rd
numberFormatter.string(for: 4) //Should produce 4th
Matt Andersen의 대답은 매우 정교하며 SDJMcHattie도 그렇습니다. 그러나 NSDateFormatter는 CPU에서 상당히 무겁고 이것을 100x라고 부르면 실제로 영향을 볼 수 있으므로 위의 답변에서 파생 된 결합 솔루션이 있습니다. (위의 내용은 여전히 정확합니다.)
NSDateFormatter는 만드는 데 엄청난 비용이 듭니다 . 한 번 생성 하고 재사용 하지만주의하십시오 : 스레드 안전이 아니므로 스레드 당 하나씩.
self.date = [NSDate date] 라고 가정합니다 .
- (NSString *)formattedDate{
static NSDateFormatter *_dateFormatter = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_dateFormatter = [[NSDateFormatter alloc] init];
_dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
_dateFormatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
});
_dateFormatter.dateFormat = [NSString stringWithFormat:@"h:mm a EEEE MMMM d'%@'", [self suffixForDayInDate:self.date]];
NSString *date = [_dateFormatter stringFromDate:self.date];
return date;
}
/ * SDJMcHattie의 코드, 이것은 배열을 사용하는 것보다 더 편리합니다 * /
- (NSString *)suffixForDayInDate:(NSDate *)date{
NSInteger day = [[[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] components:NSDayCalendarUnit fromDate:date] day];
if (day >= 11 && day <= 13) {
return @"th";
} else if (day % 10 == 1) {
return @"st";
} else if (day % 10 == 2) {
return @"nd";
} else if (day % 10 == 3) {
return @"rd";
} else {
return @"th";
}
}
출력 : 8 월 15 일 토요일 오후 3:11
그러면 "8 월 2 일 토요일 오후 10시 10 분"형식의 문자열이 제공됩니다.
-(NSString*) getTimeInString:(NSDate*)date
{
NSString* string=@"";
NSDateComponents *components = [[NSCalendar currentCalendar] components: NSCalendarUnitDay fromDate:date];
if(components.day == 1 || components.day == 21 || components.day == 31){
string = @"st";
}else if (components.day == 2 || components.day == 22){
string = @"nd";
}else if (components.day == 3 || components.day == 23){
string = @"rd";
}else{
string = @"th";
}
NSDateFormatter *prefixDateFormatter = [[NSDateFormatter alloc] init]; [prefixDateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
[prefixDateFormatter setDateFormat:[NSString stringWithFormat:@"h:mm a EEEE, d'%@' MMMM",string]];
NSString *dateString = [prefixDateFormatter stringFromDate:date];
return dateString;
}
이렇게하면 두 단계로 형식이 지정됩니다. 먼저 적절한 접미사가있는 요일 인 하위 문자열을 만든 다음 나머지 부분에 대한 형식 문자열을 만들고 이미 형식이 지정된 요일을 연결합니다.
func ordinalDate(date: Date) -> String {
let ordinalFormatter = NumberFormatter()
ordinalFormatter.numberStyle = .ordinal
let day = Calendar.current.component(.day, from: date)
let dayOrdinal = ordinalFormatter.string(from: NSNumber(value: day))!
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "h:mm a EEEE MMMM '\(dayOrdinal)'"
return dateFormatter.string(from: Date())
}
서수 일은에 의해 작성되었으므로 NumberFormatter
영어뿐만 아니라 모든 언어로 작동해야합니다.
할당을 다음 dateFormat
으로 바꾸면 현재 로케일에 대해 정렬 된 형식 문자열을 얻을 수 있습니다 .
dateFormatter.dateFormat = DateFormatter.dateFormat(fromTemplate: "h:mm a EEEE MMMM d", options: 0, locale: dateFormatter.locale)?.replacingOccurrences(of: "d", with: "'\(dayOrdinal)'")
포맷터를 만드는 데 비용이 많이 들기 때문에 자주 호출되는 코드에서이를 캐시하고 재사용해야한다는 여러 다른 사람들의 조언에 유의하십시오.
- (void)viewDidLoad
{
NSDate *date = [NSDate date];
NSDateFormatter *prefixDateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[prefixDateFormatter setDateFormat:@"yyy-dd-MM"];
date = [prefixDateFormatter dateFromString:@"2014-6-03"]; //enter yourdate
[prefixDateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
[prefixDateFormatter setDateFormat:@"EEEE MMMM d"];
NSString *prefixDateString = [prefixDateFormatter stringFromDate:date];
NSDateFormatter *monthDayFormatter = [[[NSDateFormatter alloc] init] autorelease];
[monthDayFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
[monthDayFormatter setDateFormat:@"d"];
int date_day = [[monthDayFormatter stringFromDate:date] intValue];
NSString *suffix_string = @"|st|nd|rd|th|th|th|th|th|th|th|th|th|th|th|th|th|th|th|th|th|st|nd|rd|th|th|th|th|th|th|th|st";
NSArray *suffixes = [suffix_string componentsSeparatedByString: @"|"];
NSString *suffix = [suffixes objectAtIndex:date_day];
NSString *dateString = [prefixDateString stringByAppendingString:suffix];
NSLog(@"%@", dateString);
}
또는 숫자에 대한 접미사를 원하는 경우 :
extension Int {
public func suffix() -> String {
let absSelf = abs(self)
switch (absSelf % 100) {
case 11...13:
return "th"
default:
switch (absSelf % 10) {
case 1:
return "st"
case 2:
return "nd"
case 3:
return "rd"
default:
return "th"
}
}
}
}
양수에는 5 가지 가능성이 있다고 생각합니다. 첫 번째 자리는 1이 "st"입니다. 두 번째 자리는 2가 "2nd"입니다. 세 번째 자리는 3이 "rd"입니다. 다른 경우는 "th"이거나 두 번째 자리 숫자가 1이면 위의 규칙이 적용되지 않고 "th"입니다.
Modulo 100 gives us the digit's last two numbers, so we can check for 11 to 13. Modulo 10 gives us the digit's last number, so we can check for 1, 2, 3 if not caught by the first condition.
Try that extension in playgrounds:
let a = -1
a.suffix() // "st"
let b = 1112
b.suffix() // "th"
let c = 32
c.suffix() // "nd"
Would love to see if there is an even shorter way to write this using binary operations and/or an array!
None of the answers uses the ordinal number style already present in Number Formatter in swift.
var dateString: String {
let calendar = Calendar.current
let dateComponents = calendar.component(.day, from: date)
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .ordinal
let day = numberFormatter.string(from: dateComponents as NSNumber)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM"
return day! + dateFormatter.string(from: date)
}
I added these two methods to NSDate with a category NSDate+Additions.
\- (NSString *)monthDayYear
{
NSDateFormatter * dateFormatter = NSDateFormatter.new;
[dateFormatter setDateFormat:@"MMMM d*, YYYY"];
NSString *dateString = [dateFormatter stringFromDate:self];
return [dateString stringByReplacingOccurrencesOfString:@"*" withString:[self ordinalSuffixForDay]];
}
\- (NSString *)ordinalSuffixForDay {
NSDateFormatter * dateFormatter = NSDateFormatter.new;
[dateFormatter setDateFormat:@"d"];
NSString *dateString = [dateFormatter stringFromDate:self];
NSString *suffix = @"th";
if ([dateString length] == 2 && [dateString characterAtIndex:0] == '1') {
return suffix;
}
switch ([dateString characterAtIndex:[dateString length]-1]) {
case '1':
suffix = @"st";
break;
case '2':
suffix = @"nd";
break;
case '3':
suffix = @"rd";
break;
}
return suffix;
}
You could make them more efficient by combining them and indexing the one's place digit of the day within your format string as the switch point. I opted to separate the functionality so the ordinal suffixes can be called separately for different date formats.
- (NSString *)dayWithSuffixForDate:(NSDate *)date {
NSInteger day = [[[NSCalendar currentCalendar] components:NSDayCalendarUnit fromDate:date] day];
NSString *dayOfMonthWithSuffix, *suffix = nil ;
if(day>0 && day <=31)
{
switch (day)
{
case 1:
case 21:
case 31: suffix = @"st";
break;
case 2:
case 22: suffix = @"nd";
break;
case 3:
case 23: suffix = @"rd";
break;
default: suffix = @"th";
break;
}
dayOfMonthWithSuffix = [NSString stringWithFormat:@"%ld%@", (long)day , suffix];
}
return dayOfMonthWithSuffix;
}
The NSDateFormatter documentation says that all the format options it supports are listed in TR35.
Why do you want this? If you're making something for a machine to parse, you should use ISO 8601 format, or RFC 2822 format if you have to. Neither one of those requires or allows an ordinal suffix.
If you're showing dates to the user, you should use one of the formats from the user's locale settings.
'Program Tip' 카테고리의 다른 글
RecyclerView에서 단일 선택 (0) | 2020.12.02 |
---|---|
sudo : 포트 : 명령을 찾을 수 없습니다. (0) | 2020.12.02 |
tcpdump를 사용하여 HTTP 요청, 응답 헤더 및 응답 본문을 가져올 수 있습니까? (0) | 2020.12.02 |
오류없이 Symfony2 잘못된 양식 (0) | 2020.12.02 |
ostream을 표준 문자열로 변환 (0) | 2020.12.02 |