Nsdate get Rok / Miesiąc/Dzień

Jak mogę uzyskać Rok/Miesiąc / Dzień NSDate obiektu, bez żadnych innych informacji? Zdaję sobie sprawę, że prawdopodobnie mógłbym to zrobić z czymś podobnym do tego:

NSCalendar *cal = [[NSCalendar alloc] init];
NSDateComponents *components = [cal components:0 fromDate:date];
int year = [components year];
int month = [components month];
int day = [components day];

Ale to wydaje się być dużo kłopotów dla czegoś tak prostego, jak uzyskanie NSDate'S Rok/Miesiąc / Dzień. Czy jest jakieś inne rozwiązanie?

Author: Richard J. Ross III, 2010-09-12

17 answers

Ponieważ jest to najwyraźniej moja najpopularniejsza odpowiedź, postaram się ją edytować, aby zawierała trochę więcej informacji.

Pomimo swojej nazwy, NSDate sama w sobie oznacza punkt w czasie Maszyny, a nie datę. Nie ma korelacji między punktem w czasie określonym przez NSDate a rokiem, miesiącem lub dniem. W tym celu musisz odwołać się do kalendarza. Każdy dany punkt w czasie zwróci inną informację o dacie w zależności od tego, na jaki kalendarz patrzysz (daty nie są takie same w na przykład kalendarze gregoriańskie i Żydowskie), i chociaż Kalendarz gregoriański jest najczęściej używanym kalendarzem na świecie-zakładam - jesteśmy trochę stronniczy, że NSDate powinien zawsze go używać. NSDate, na szczęście, jest o wiele bardziej dwupartyjny.


Jak już wspomniałeś, czas i data będą musiały przejść przez NSCalendar, ale jest na to prostszy sposób:
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:[NSDate date]];

Generuje obiekt NSDateComponents zawierający dzień, miesiąc i rok z bieżącego systemu kalendarz na bieżący dzień. (Uwaga: niekoniecznie jest to aktualny kalendarz określony przez użytkownika , tylko domyślny systemowy.)

Oczywiście, jeśli używasz innego kalendarza lub daty, Możesz to łatwo zmienić. Listę dostępnych kalendarzy i jednostek kalendarza można znaleźć w NSCalendar Numer klasy . Więcej informacji o NSDateComponents można znaleźć w NSDateComponents Numer klasy .


W celach informacyjnych, dostęp do poszczególnych komponenty z NSDateComponents jest dość proste:

NSInteger day = [components day];
NSInteger month = [components month];
NSInteger year = [components year];

Musisz tylko pamiętać: NSDateComponents nie będzie zawierać poprawnych informacji dla pól, o które prosisz, chyba że wygenerujesz je z tymi poprawnymi informacjami(np. poproś {[6] } o podanie tych informacji z NSCalendarUnits). NSDateComponents nie zawierają w sobie żadnych informacji referencyjnych - są to proste struktury, które przechowują liczby, do których możesz uzyskać dostęp. Jeśli chcesz również uzyskać erę, na przykład, z NSDateComponents, będziesz musiał karmić generator metoda z NSCalendar z flagą NSCalendarUnitEra.

 594
Author: Itai Ferber,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-07-17 19:48:34

Można uzyskać oddzielny składnik NSDate za pomocą NSDateFormatter:

NSDateFormatter *df = [[NSDateFormatter alloc] init];

[df setDateFormat:@"dd"];
myDayString = [df stringFromDate:[NSDate date]];

[df setDateFormat:@"MMM"];
myMonthString = [df stringFromDate:[NSDate date]];

[df setDateFormat:@"yy"];
myYearString = [df stringFromDate:[NSDate date]];

Jeśli Chcesz otrzymać numer miesiąca zamiast skrótu, użyj "MM". Jeśli chcesz uzyskać liczby całkowite, użyj [myDayString intValue];

 49
Author: skocko76,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-04-07 08:22:03

Żeby przerobić Itai ' s excellent (i działa!) kod, oto jak wyglądałaby przykładowa Klasa pomocnicza, zwracająca wartość year danej zmiennej NSDate.

Jak widzisz, łatwo jest zmodyfikować ten kod, aby uzyskać miesiąc lub dzień.

+(int)getYear:(NSDate*)date
{
    NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:date];

    int year = [components year];
    int month = [components month];
    int day = [components day];

    return year;
}

(nie mogę uwierzyć, że musimy napisać nasze własne podstawowe funkcje daty iOS, takie jak ta, w 2013...)

Jeszcze jedno: nigdy nie używaj do porównywania dwóch wartości NSDate.

XCode chętnie przyjmie taki kod (bez błędów i ostrzeżeń), ale jego wyniki są loterią. Należy użyć funkcji "compare", aby porównać NSDates:

if ([date1 compare:date2] == NSOrderedDescending) {
    // date1 is greater than date2        
}
 16
Author: Mike Gledhill,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-05-16 09:43:20

W Swift 2.0:

    let date = NSDate()
    let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)!
    let components = calendar.components([.Month, .Day], fromDate: date)

    let (month, day) = (components.month, components.day)
 13
Author: NatashaTheRobot,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-23 17:34:40

Piszę tę odpowiedź, ponieważ jest to jedyne podejście, które nie daje opcji powrotu z NSDateComponent zmiennych i / lub wymusić rozpakowanie tych zmiennych(również dla Swift 3).

Swift 3

let date = Date()
let cal = Calendar.current
let year = cal.component(.year, from: date)
let month = cal.component(.month, from: date)
let day = cal.component(.day, from: date)

Swift 2

let date = NSDate()
let cal = NSCalendar.currentCalendar()
let year = cal.component(.Year, fromDate: date)
let month = cal.component(.Month, fromDate: date)
let day = cal.component(.Day, fromDate: date)

Bonus Swift 3 fun version

let date = Date()
let component = { (unit) in return Calendar.current().component(unit, from: date) }
let year = component(.year)
let month = component(.month)
let day = component(.day)
 10
Author: Kevin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-05 14:02:13

Nowy W iOS 8

ObjC

NSDate *date = [NSDate date];
NSInteger era, year, month, day;
[[NSCalendar currentCalendar] getEra:&era year:&year month:&month day:&day fromDate:date];

Swift

let date = NSDate.init()
var era = 0, year = 0, month = 0, day = 0
NSCalendar.currentCalendar().getEra(&era, year:&year, month:&month, day:&day, fromDate: date)
 7
Author: Yuchen Zhong,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-26 16:39:59

Jeśli celujesz w system iOS 8+, możesz użyć nowych metod wygody NSCalendar, aby osiągnąć to w bardziej zwięzłym formacie.

Najpierw Utwórz NSCalendar i użyj tego, co jest wymagane NSDate.

NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *date = [NSDate date];

Można wyodrębnić składniki pojedynczo poprzez component:fromDate:

NSInteger year = [calendar component:NSCalendarUnitYear fromDate:date];
NSInteger month = [calendar component:NSCalendarUnitMonth fromDate:date];
NSInteger day = [calendar component:NSCalendarUnitDay fromDate:date];

Lub, jeszcze bardziej zwięźle, użyj NSInteger wskaźników poprzez getEra:year:month:day:fromDate:

NSInteger year, month, day;
[calendar getEra:nil year:&year month:&month day:&day fromDate:date];
Aby uzyskać więcej informacji i przykładów, sprawdź łatwa manipulacja NSDate w systemie iOS 8. Zastrzeżenie, napisałem post.
 4
Author: Joe Masilotti,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-10 11:47:40

Począwszy od iOS 8.0 (i OS X 10) możesz użyć metody component , aby uprościć uzyskanie pojedynczego komponentu daty w następujący sposób:

int year = [[NSCalendar currentCalendar] component:NSCalendarUnitYear fromDate:[NSDate date]];

Powinno to uprościć i miejmy nadzieję, że zostanie to skutecznie wdrożone.

 3
Author: Christopher King,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-09-16 01:18:20

Jeśli chcesz uzyskać poszczególne komponenty Nsdate z NSDate, zdecydowanie potrzebujesz rozwiązania zaproponowanego przez Itai Ferber. Ale jeśli chcesz , aby przejść z NSDate bezpośrednio do NSString, można użyć NSDateFormatter .

 2
Author: gumbo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 11:47:17
    NSDate *currDate = [NSDate date];
    NSCalendar*       calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents* components = [calendar components:NSDayCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit fromDate:currDate];
    NSInteger         day = [components day];
    NSInteger         month = [components month];
    NSInteger         year = [components year];
    NSLog(@"%d/%d/%d", day, month, year);
 2
Author: Linh Nguyen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-04-08 03:29:07

Oto rozwiązanie w języku Swift:

let todayDate = NSDate()
let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)!

// Use a mask to extract the required components. Extract only the required components, since it'll be expensive to compute all available values.
let components = calendar.components(.CalendarUnitYear | .CalendarUnitMonth | .CalendarUnitDay, fromDate: todayDate)

var (year, month, date) = (components.year, components.month, components.day) 
 2
Author: Nitin Nain,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-06-25 07:02:26

Spróbuj:

    NSString *birthday = @"06/15/1977";
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"MM/dd/yyyy"];
    NSDate *date = [formatter dateFromString:birthday];
    if(date!=nil) {
        NSInteger age = [date timeIntervalSinceNow]/31556926;
        NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:date];
        NSInteger day = [components day];
        NSInteger month = [components month];
        NSInteger year = [components year];

        NSLog(@"Day:%d Month:%d Year:%d Age:%d",day,month,year,age);
    }
    [formatter release];
 1
Author: loretoparisi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-01-17 09:40:56

/ Align = "left" / x

extension NSDate {
    func currentDateInDayMonthYear() -> String {
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "d LLLL yyyy"
        return dateFormatter.stringFromDate(self)
    }
}

Możesz go użyć jako

NSDate().currentDateInDayMonthYear()

Wyjście

6 March 2016
 1
Author: Alserda,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-03-06 22:41:03

Spróbuj tego . . .

Fragment kodu:

 NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:[NSDate date]];
 int year = [components year];
 int month = [components month];
 int day = [components day];

Podaje bieżący rok, miesiąc, datę

 1
Author: Yogeesh H T,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-03-18 15:29:47

Robię to w ten sposób ....

NSDate * mydate = [NSDate date];

NSCalendar * mycalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

NSCalendarUnit units = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;

NSDateComponents * myComponents  = [mycalendar components:units fromDate:mydate];

NSLog(@"%d-%d-%d",myComponents.day,myComponents.month,myComponents.year);
 0
Author: Shaik Riyaz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-05-20 11:46:40

Aby uzyskać czytelny dla człowieka ciąg znaków (dzień, miesiąc, rok), możesz wykonać:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
NSString *string = [dateFormatter stringFromDate:dateEndDate];
 0
Author: mirap,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-06 10:59:18

Swift

Łatwiejszy sposób na uzyskanie dowolnych elementów date jako opcjonalnego ciągu znaków.

extension Date {

  // Year 
  var currentYear: String? {
    return getDateComponent(dateFormat: "yy")
    //return getDateComponent(dateFormat: "yyyy")
  }

  // Month 
  var currentMonth: String? {
    return getDateComponent(dateFormat: "M")
    //return getDateComponent(dateFormat: "MM")
    //return getDateComponent(dateFormat: "MMM")
    //return getDateComponent(dateFormat: "MMMM")
  }


  // Day
  var currentDay: String? {
    return getDateComponent(dateFormat: "dd")
    //return getDateComponent(dateFormat: "d")
  }


  func getDateComponent(dateFormat: String) -> String? {
    let format = DateFormatter()
    format.dateFormat = dateFormat
    return format.string(from: self)
  }


}

let today = Date()
print("Current Year - \(today.currentYear)")  // result Current Year - Optional("2017")
print("Current Month - \(today.currentMonth)")  // result Current Month - Optional("7")
print("Current Day - \(today.currentDay)")  // result Current Day - Optional("10")
 0
Author: Krunal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-10 12:21:38