NSDate 获取年/月/日

发布于 2024-09-19 17:42:35 字数 359 浏览 4 评论 0原文

在没有其他信息的情况下,如何获取 NSDate 对象的年/月/日?我意识到我可能可以用类似的东西来做到这一点:

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

但这对于像获取 NSDate 的年/月/日这样简单的事情来说似乎是一大堆麻烦。还有其他解决办法吗?

How can I get the year/month/day of a NSDate object, given no other information? I realize that I could probably do this with something similar to this:

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

But that seems to be a whole lot of hassle for something as simple as getting a NSDate's year/month/day. Is there any other solution?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(17

爱格式化 2024-09-26 17:42:36

我写这个答案是因为它是唯一一种不会从 NSDateComponent 变量返回选项和/或强制解开这些变量的方法(也适用于 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 趣味版

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)

I'm writing this answer because it's the only approach that doesn't give you optionals back from NSDateComponent variables and/or force unwrapping those variables (also for 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)
戴着白色围巾的女孩 2024-09-26 17:42:36

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)

New In 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)
眉黛浅 2024-09-26 17:42:36

从 iOS 8.0(和 OS X 10)开始,您可以使用 component 方法来简化获取单个日期组件的过程,如下所示:

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

应该让事情变得更简单,希望这可以有效实现。

As of iOS 8.0 (and OS X 10) you can use the component method to simplify getting a single date component like so:

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

Should make things simpler and hopefully this is implemented efficiently.

安人多梦 2024-09-26 17:42:36

如果您的目标是 iOS 8+,您可以使用新的 NSCalendar 便捷方法以更简洁的格式实现此目的。

首先创建一个 NSCalendar 并使用所需的任何 NSDate

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

您可以通过 component:fromDate: 单独提取组件

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

,或者更简洁地,通过 getEra:year:month:day:fromDate: 使用 NSInteger 指针>

NSInteger year, month, day;
[calendar getEra:nil year:&year month:&month day:&day fromDate:date];

有关更多信息和示例,请查看iOS 8 中的 NSDate 操作变得轻松。免责声明,我写了这篇文章。

If you are targeting iOS 8+ you can use the new NSCalendar convenience methods to achieve this in a more terse format.

First create an NSCalendar and use whatever NSDate is required.

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

You could extract components individually via component:fromDate:

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

Or, even more succinctly, use NSInteger pointers via getEra:year:month:day:fromDate:

NSInteger year, month, day;
[calendar getEra:nil year:&year month:&month day:&day fromDate:date];

For more information and examples check out NSDate Manipulation Made Easy in iOS 8. Disclaimer, I wrote the post.

紫瑟鸿黎 2024-09-26 17:42:36
    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);
    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);
↙厌世 2024-09-26 17:42:36

如果您希望从 NSDate 获取单独的 NSDateComponents,您肯定需要 Itai Ferber 建议的解决方案。但是如果你想从 NSDate 直接转换为 NSString,你可以使用 NSDateFormatter

If you wish to get the individual NSDateComponents from NSDate, you would definitely need the solution suggested by Itai Ferber. But if you want to go from NSDate directly to an NSString, you can use NSDateFormatter.

风筝有风,海豚有海 2024-09-26 17:42:36

请尝试以下操作:

    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];

Try the following:

    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];
无法回应 2024-09-26 17:42:36

这是 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) 

Here's the solution in 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) 
余生共白头 2024-09-26 17:42:36

试试这个。 。 。

代码片段:

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

它给出当前的年、月、日

Try this . . .

Code snippet:

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

It gives current year, month, date

呆萌少年 2024-09-26 17:42:36

Swift

更简单的方法来获取日期的任何元素作为可选字符串。

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")

Swift

Easier way to get any elements of date as an optional String.

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")
遗弃M 2024-09-26 17:42:36

Swift 2.x

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

您可以将其用作

NSDate().currentDateInDayMonthYear()

输出

6 March 2016

Swift 2.x

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

You can use it as

NSDate().currentDateInDayMonthYear()

Output

6 March 2016
最初的梦 2024-09-26 17:42:36

我这样做......

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);

i do in this way ....

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);
半寸时光 2024-09-26 17:42:36

要获得人类可读的字符串(日、月、年),您可以这样做:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
NSString *string = [dateFormatter stringFromDate:dateEndDate];

To get human readable string (day, month, year), you may do:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
NSString *string = [dateFormatter stringFromDate:dateEndDate];
荒人说梦 2024-09-26 17:42:35

因为这显然是我最受欢迎的答案,所以我将尝试编辑它以包含更多信息。

尽管有它的名字,NSDate 本身只是标记机器时间中的一个点,而不是日期。 NSDate 指定的时间点与年、月或日之间没有关联。为此,您必须参考日历。任何给定的时间点都会根据您查看的日历返回不同的日期信息(例如,公历和犹太历中的日期不相同),而公历是世界上使用最广泛的日历。 world - 我假设 - 我们有点偏向于 NSDate 应该始终使用它。幸运的是,NSDate 的两党合作程度要高得多。


正如您提到的,获取日期和时间必须通过 NSCalendar 传递,但有一种更简单的方法:

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

生成一个包含日、月的 NSDateComponents 对象,以及当前系统日历中的年份。 (注意:这不一定是当前用户指定的日历,而只是默认的系统日历。)

当然,如果您使用不同的日历或日期,你可以轻松改变这一点。可用日历和日历单位的列表可以在 NSCalendar 类参考。有关 NSDateComponents 的更多信息可以在 NSDateComponents 类参考


作为参考,从 NSDateComponents 访问各个组件相当简单:

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

您只需要注意:NSDateComponents 不会包含您要求的任何字段的有效信息,除非您生成他们与该有效信息(即请求 NSCalendar 提供该信息与 NSCalendarUnit s)。 NSDateComponents 本身不包含任何参考信息 - 它们只是保存数字供您访问的简单结构。例如,如果您还想从 NSDateComponents 中获取一个时代,则必须使用 NSCalendarUnitEraNSCalendar 提供生成器方法> 旗帜。

Because this is apparently my most popular answer, I'll try to edit it to contain a little bit more information.

Despite its name, NSDate in and of itself simply marks a point in machine time, not a date. There's no correlation between the point in time specified by an NSDate and a year, month, or day. For that, you have to refer to a calendar. Any given point in time will return different date information based on what calendar you're looking at (dates are not the same in both the Gregorian and Jewish calendars, for instance), and while the Gregorian calendar is the most widely used calendar in the world - I'm assuming - we're a little biased that NSDate should always use it. NSDate, luckily, is far more bipartisan.


Getting date and time is going to have to pass through NSCalendar, as you mentioned, but there's a simpler way to do it:

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

That generates an NSDateComponents object containing the day, month, and year from the current system calendar for the current day. (Note: this isn't necessarily the current user-specified calendar, just the default system one.)

Of course, if you're using a different calendar or date, you can easily change that. A list of available calendars and calendar units can be found in the NSCalendar Class Reference. More information about NSDateComponents can be found in the NSDateComponents Class Reference.


For reference, accessing individual components from the NSDateComponents is rather easy:

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

You just have to be mindful: NSDateComponents won't contain valid information for any fields you ask for unless you generated them with that valid information (i.e. request NSCalendar to provide that information with NSCalendarUnits). NSDateComponents contain no reference information in and of themselves - they're just simple structures that hold numbers for you to access. If you want to also get an era, for instance, out of NSDateComponents, you'll have to feed the generator method from NSCalendar with the NSCalendarUnitEra flag.

以为你会在 2024-09-26 17:42:35

您可以使用 NSDateFormatter 获取 NSDate 的单独组件:

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]];

如果您希望获取月份数字而不是缩写,请使用“MM”。如果您想获取整数,请使用[myDayString intValue];

You can get separate component of a NSDate using 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]];

If you wish to get month's number instead of abbreviation, use "MM". If you wish to get integers, use [myDayString intValue];

滥情空心 2024-09-26 17:42:35

只是为了重写 Itai 的优秀(并且有效!)代码,下面是示例帮助程序类的样子,用于返回给定 NSDate 变量的 year 值。

正如您所看到的,修改此代码以获取月份或日期非常容易。

+(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;
}

(我不敢相信我们必须在 2013 年编写这样的我们自己的基本 iOS 日期函数......)

另一件事:永远不要使用 <<和>比较两个 NSDate 值。

XCode 会很乐意接受这样的代码(没有任何错误或警告),但它的结果是彩票。您必须使用“比较”函数来比较 NSDate:

if ([date1 compare:date2] == NSOrderedDescending) {
    // date1 is greater than date2        
}

Just to reword Itai's excellent (and working!) code, here's what a sample helper class would look like, to return the year value of a given NSDate variable.

As you can see, it's easy enough to modify this code to get the month or day.

+(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;
}

(I can't believe we're having to write our own basic iOS date functions like this, in 2013...)

One other thing: don't ever use < and > to compare two NSDate values.

XCode will happily accept such code (without any errors or warnings), but its results are a lottery. You must use the "compare" function to compare NSDates:

if ([date1 compare:date2] == NSOrderedDescending) {
    // date1 is greater than date2        
}
日裸衫吸 2024-09-26 17:42:35

在斯威夫特 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)

In 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)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文