比较两个日期的大小 NSDate获取当前日期 进行比较

本文介绍如何使用Objective-C来获取当前的年月日、时分秒、周几等日期时间信息,并通过NSDateFormatter格式化输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

取得当前的年月日,当前的时分秒获得,周几和星期几获得


NSDate*date = [NSDate date];

NSCalendar*calendar = [NSCalendar currentCalendar];

NSDateComponents*comps;

 

// 年月日获得

comps =[calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit |NSDayCalendarUnit)

                                      fromDate:date];

NSIntegeryear = [comps year];

NSIntegermonth = [comps month];

NSIntegerday = [comps day];

NSLog(@"year:%d month: %d, day: %d", year, month, day);

 

//当前的时分秒获得

comps =[calendar components:(NSHourCalendarUnit | NSMinuteCalendarUnit |NSSecondCalendarUnit)

                                      fromDate:date];

NSIntegerhour = [comps hour];

NSIntegerminute = [comps minute];

NSIntegersecond = [comps second];

NSLog(@"hour:%d minute: %d second: %d", hour, minute, second);

 

// 周几和星期几获得

comps =[calendar components:(NSWeekCalendarUnit | NSWeekdayCalendarUnit |NSWeekdayOrdinalCalendarUnit)

                                      fromDate:date];

NSInteger week = [comps week]; // 今年的第几周

NSIntegerweekday = [comps weekday]; // 星期几(注意,周日是“1”,周一是“2”。。。。)

NSIntegerweekdayOrdinal = [comps weekdayOrdinal]; // 这个月的第几周

NSLog(@"week:%d weekday: %d weekday ordinal: %d", week, weekday, weekdayOrdinal);

 

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

       if(dateSwitch.on)

       [dateFormattersetDateFormat:@"dd-MMM-yyy,hh:mm:ss"];

       else

       [dateFormatter setDateFormat:@"hh:mm:ss"];

       labelTime.text = [dateFormatter stringFromDate:[NSDatedate]];

       labelTime.font = [UIFontsystemFontOfSize:fontSlider.value];

       [dateFormatter release];


注意:[calendar components:(NSWeekCalendarUnit | NSWeekdayCalendarUnit |NSWeekdayOrdinalCalendarUnit)  标志位,不能一次设置太多,不好用,我也不知道为什么,有待考证~

### 比较两个字符串格式的日期大小 在编程中比较两个字符串格式的日期大小,可以通过解析这些字符串并将其转换为相应的日期对象后再进行比较。以下是几种常见编程语言中的实现方式: #### C# 在 C# 中可以先将字符串转换为 `DateTime` 对象,然后再通过内置的方法进行比较[^1]。 ```csharp string dateString1 = "2023-10-01"; string dateString2 = "2023-10-15"; try { DateTime date1 = DateTime.ParseExact(dateString1, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture); DateTime date2 = DateTime.ParseExact(dateString2, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture); if (date1 > date2) Console.WriteLine("Date1 is later than Date2."); else if (date1 < date2) Console.WriteLine("Date1 is earlier than Date2."); else Console.WriteLine("Both dates are equal."); } catch (FormatException ex) { Console.WriteLine($"Invalid format: {ex.Message}"); } ``` #### Java Java 提供了多种方法来处理日期和时间数据。其中一种常用的方式是利用 `SimpleDateFormat` 类将字符串解析为 `Date` 或者 `LocalDate` 对象后进行比较[^4]。 ```java import java.text.ParseException; import java.text.SimpleDateFormat; public class Main { public static void main(String[] args) throws ParseException { String dateString1 = "2023-10-01"; String dateString2 = "2023-10-15"; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); try { java.util.Date date1 = sdf.parse(dateString1); java.util.Date date2 = sdf.parse(dateString2); if (date1.after(date2)) System.out.println("Date1 is after Date2."); else if (date1.before(date2)) System.out.println("Date1 is before Date2."); else System.out.println("Both dates are the same."); } catch(ParseException e){ System.err.println(e.getMessage()); } } } ``` 对于更现代的应用场景,推荐使用 `java.time.LocalDate` 来代替旧式的 `Date` 和 `Calendar` API[^4]: ```java import java.time.LocalDate; import java.time.format.DateTimeParseException; public class Main { public static void main(String[] args) { String dateString1 = "2023-10-01"; String dateString2 = "2023-10-15"; try { LocalDate date1 = LocalDate.parse(dateString1); LocalDate date2 = LocalDate.parse(dateString2); if (date1.isAfter(date2)) System.out.println("Date1 is after Date2."); else if (date1.isBefore(date2)) System.out.println("Date1 is before Date2."); else System.out.println("Both dates are the same."); } catch(DateTimeParseException e){ System.err.println(e.getMessage()); } } } ``` #### iOS/Swift 在 Swift/iOS 开发环境中,通常会采用 `NSDateFormatter` 将字符串转化为 `NSDate` 后调用其 `compare:` 方法完成对比操作[^3]。 ```swift let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd" if let date1 = dateFormatter.date(from: "2023-10-01"), let date2 = dateFormatter.date(from: "2023-10-15") { switch date1.compare(date2) { case .orderedAscending: print("Date1 occurs before Date2.") case .orderedSame: print("Date1 and Date2 occur on the same day.") case .orderedDescending: print("Date1 occurs after Date2.") @unknown default: fatalError("Unexpected comparison result") } } else { print("Error parsing one or both of the provided strings as a valid date.") } ``` 以上展示了不同编程环境下如何有效地执行两字符串形式表示之日期间的相对顺序判断逻辑过程。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值