xcode 获取第一个日期,最后一个月份?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10717574/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get firstdate, lastdate of month?
提问by Alice Chen
I want to get firstdate、lastdate of month,I try
我想得到第一个、最后一个月的日期,我试试
NSDateComponents *components = [calendar components:units fromDate:[NSDate date]];
[components setDay:1];
self.currentDate = [calendar dateFromComponents:components];
int m = components.month;
int y = components.year;
int d = components.day;
log: 2012,5,1
How can i get lastdate od month?
我怎样才能得到 lastdate od 月份?
please give me some advice,thank you!!
请给我一些建议,谢谢!!
回答by Ashley Mills
Some NSDate
category methods I wrote will help you:
NSDate
我写的一些分类方法会帮助你:
Here's an easy way to find the start of a month:
这是查找一个月开始的简单方法:
(NSDate *) startOfMonth
{
NSCalendar * calendar = [NSCalendar currentCalendar];
NSDateComponents * currentDateComponents = [calendar components: NSYearCalendarUnit | NSMonthCalendarUnit fromDate: self];
NSDate * startOfMonth = [calendar dateFromComponents: currentDateComponents];
return startOfMonth;
}
All it does is take the year and month components from the current day, then convert back to a date again.
它所做的只是从当天获取年和月的组件,然后再次转换回日期。
For the end of the month, I use a couple of methods:
在月底,我使用了几种方法:
- (NSDate *) dateByAddingMonths: (NSInteger) monthsToAdd
{
NSCalendar * calendar = [NSCalendar currentCalendar];
NSDateComponents * months = [[NSDateComponents alloc] init];
[months setMonth: monthsToAdd];
return [calendar dateByAddingComponents: months toDate: self options: 0];
}
and
和
- (NSDate *) endOfMonth
{
NSCalendar * calendar = [NSCalendar currentCalendar];
NSDate * plusOneMonthDate = [self dateByAddingMonths: 1];
NSDateComponents * plusOneMonthDateComponents = [calendar components: NSYearCalendarUnit | NSMonthCalendarUnit fromDate: plusOneMonthDate];
NSDate * endOfMonth = [[calendar dateFromComponents: plusOneMonthDateComponents] dateByAddingTimeInterval: -1]; // One second before the start of next month
return endOfMonth;
}
This is a 3 step process - add one month to the current date, find the start of the next month, then subtract 1 second to find the end of this month.
这是一个 3 步过程 - 在当前日期上加一个月,找到下个月的开始,然后减去 1 秒来找到这个月的月底。
Swift 3
斯威夫特 3
extension Date {
func startOfMonth() -> Date? {
let calendar = Calendar.current
let currentDateComponents = calendar.dateComponents([.year, .month], from: self)
let startOfMonth = calendar.date(from: currentDateComponents)
return startOfMonth
}
func dateByAddingMonths(_ monthsToAdd: Int) -> Date? {
let calendar = Calendar.current
var months = DateComponents()
months.month = monthsToAdd
return calendar.date(byAdding: months, to: self)
}
func endOfMonth() -> Date? {
guard let plusOneMonthDate = dateByAddingMonths(1) else { return nil }
let calendar = Calendar.current
let plusOneMonthDateComponents = calendar.dateComponents([.year, .month], from: plusOneMonthDate)
let endOfMonth = calendar.date(from: plusOneMonthDateComponents)?.addingTimeInterval(-1)
return endOfMonth
}
}
Swift 2
斯威夫特 2
extension NSDate {
func startOfMonth() -> NSDate? {
let calendar = NSCalendar.currentCalendar()
let currentDateComponents = calendar.components(.CalendarUnitYear | .CalendarUnitMonth, fromDate: self)
let startOfMonth = calendar.dateFromComponents(currentDateComponents)
return startOfMonth
}
func dateByAddingMonths(monthsToAdd: Int) -> NSDate? {
let calendar = NSCalendar.currentCalendar()
let months = NSDateComponents()
months.month = monthsToAdd
return calendar.dateByAddingComponents(months, toDate: self, options: nil)
}
func endOfMonth() -> NSDate? {
let calendar = NSCalendar.currentCalendar()
if let plusOneMonthDate = dateByAddingMonths(1) {
let plusOneMonthDateComponents = calendar.components(.CalendarUnitYear | .CalendarUnitMonth, fromDate: plusOneMonthDate)
let endOfMonth = calendar.dateFromComponents(plusOneMonthDateComponents)?.dateByAddingTimeInterval(-1)
return endOfMonth
}
return nil
}
}
回答by Nazir
Try this trick.
试试这个技巧。
Day Param: 1 is to Get first date of this month
日期参数:1 是获取本月的第一个日期
Day Param: 0 is to Get last date of this month by getting last date of month previous to next month (means this month))
日期参数:0 是通过获取下个月的上个月的最后日期来获取本月的最后日期(表示本月))
- (void)returnDate:(NSDate *)date {
NSCalendar * calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit;
NSDateComponents *comps = [calendar components:unitFlags fromDate:date];
NSDate * firstDateOfMonth = [self returnDateForMonth:comps.month year:comps.year day:1];
NSDate * lastDateOfMonth = [self returnDateForMonth:comps.month+1 year:comps.year day:0];
NSLog(@"date %@", date); // date 2013-06-20
NSLog(@"First %@", firstDateOfMonth); // firstDateOfMonth 2013-06-01
NSLog(@"Last %@", lastDateOfMonth); // lastDateOfMonth 2013-06-30
}
Next
下一个
- (NSDate *)returnDateForMonth:(NSInteger)month year:(NSInteger)year day:(NSInteger)day {
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setDay:day];
[components setMonth:month];
[components setYear:year];
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
return [gregorian dateFromComponents:components];
}
Don't forget for right Date Formater
不要忘记正确的日期格式化程序
Updated for IOS 8.0
为 IOS 8.0 更新
- (void)returnDate:(NSDate *)date {
NSCalendar * calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth;
NSDateComponents *comps = [calendar components:unitFlags fromDate:date];
NSDate * firstDateOfMonth = [self returnDateForMonth:comps.month year:comps.year day:1];
NSDate * lastDateOfMonth = [self returnDateForMonth:comps.month+1 year:comps.year day:0];
NSLog(@"date %@", date); // date 2013-06-20
NSLog(@"First %@", firstDateOfMonth); // firstDateOfMonth 2013-06-01
NSLog(@"Last %@", lastDateOfMonth); // lastDateOfMonth 2013-06-30
}
Next
下一个
- (NSDate *)returnDateForMonth:(NSInteger)month year:(NSInteger)year day:(NSInteger)day {
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setDay:day];
[components setMonth:month];
[components setYear:year];
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
return [gregorian dateFromComponents:components];
}
Now your are working with:
现在您正在使用:
- NSCalendarUnitYear
- NSCalendarUnitWeekOfMonth
- NSCalendarIdentifierGregorian
- NSCalendarUnitYear
- NSCalendarUnitWeekOfMonth
- NSCalendarIdentifierGregorian
回答by Scott Means
Ok, since I'm rolling my own calendar control, I went ahead and created a NSCalendar
category. Here's my lastOfMonth
method:
好的,因为我正在滚动我自己的日历控件,所以我继续创建了一个NSCalendar
类别。这是我的lastOfMonth
方法:
- (NSDate *)lastOfMonth:(NSDate *)date
{
NSDateComponents *dc = [self components:NSEraCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit fromDate:date];
NSRange dim = [self rangeOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forDate:date];
dc.day = dim.length;
return [self dateFromComponents:dc];
}
回答by Dasoga
For Swift 2.0to get the first day of the current month:
对于Swift 2.0获取当月的第一天:
let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let dateComponents = calendar.components([NSCalendarUnit.Month, NSCalendarUnit.Year], fromDate: date)
let firstDay = self.returnDateForMonth(dateComponents.month, year: dateComponents.year, day: 1)
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd-MMM-yy"
print("First day of this month: \(firstDay)") // 01-Sep-15
And the function to do this:
以及执行此操作的功能:
func returnDateForMonth(month:NSInteger, year:NSInteger, day:NSInteger)->NSDate{
let comp = NSDateComponents()
comp.month = month
comp.year = year
comp.day = day
let grego = NSCalendar.currentCalendar()
return grego.dateFromComponents(comp)!
}
回答by jose920405
In Swift based in Nazir's answer
在基于纳齐尔的答案的斯威夫特
func getFirstAndLastDateOfMonth(date: NSDate) -> (fistDateOfMonth: NSDate, lastDateOfMonth: NSDate) {
let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
let calendarUnits = NSCalendarUnit.CalendarUnitYear | NSCalendarUnit.CalendarUnitMonth
let dateComponents = calendar?.components(calendarUnits, fromDate: date)
let fistDateOfMonth = self.returnedDateForMonth(dateComponents!.month, year: dateComponents!.year, day: 1)
let lastDateOfMonth = self.returnedDateForMonth(dateComponents!.month + 1, year: dateComponents!.year, day: 0)
println("fistDateOfMonth \(fistDateOfMonth)")
println("lastDateOfMonth \(lastDateOfMonth)")
return (fistDateOfMonth!,lastDateOfMonth!)
}
func returnedDateForMonth(month: NSInteger, year: NSInteger, day: NSInteger) -> NSDate? {
var components = NSDateComponents()
components.day = day
components.month = month
components.year = year
let gregorian = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
return gregorian!.dateFromComponents(components)
}
回答by Abhishek Singh
You can get last date of month using :-
您可以使用:-
NSDate currDate=[NSDate date];
-(NSString *)getLastDateMonth:(NSDate *)currDate{
NSCalendar *gregCalendar=[[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents *components=[gregCalendar components:NSMonthCalendarUnit|NSYearCalendarUnit fromDate:currDate];
NSInteger month=[components month];
NSInteger year=[components year];
if (month==12) {
[components setYear:year+1];
[components setMonth:1];
} else {
[components setMonth:month+1];
}
[components setDay:1];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateStyle:NSDateFormatterShortStyle];
NSString *lastDateOfMonth = [dateFormat stringFromDate:(NSDate *)[[gregCalendar dateFromComponents:components] dateByAddingTimeInterval:-86400]];
dateFormat=nil;
return lastDateOfMonth;
}
回答by Abduliam Rehmanius
Looks like there is no need for any tricks or hacks, NSCalendar's rangeOfUnitdoes the job pretty nicely:
看起来不需要任何技巧或技巧,NSCalendar的rangeOfUnit可以很好地完成这项工作:
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *dc = [[NSDateComponents alloc] init];
dc.year = 1947;
dc.month = 8; //desired month
//calculate start date
dc.day = 1; //As far as I can think start date of a month will always be 1
NSDate *start = [cal dateFromComponents:dc];
//calculate last date of month
NSRange dim = [cal rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:start]; // we used start date as it has the same month & year value as desired
dc.day=dim.length; //this is the simply the last day of the desired month
NSDate *last = [[NSCalendar currentCalendar] dateFromComponents:dc];
Log the values for verification:
记录验证值:
NSLog(@"Start day of month Date: %@", start);
NSLog(@"Last day of month Date: %@", last);
Apple docs on NSCalendar rangeOfUnit: https://developer.apple.com/documentation/foundation/nscalendar/1418344-rangeofunit
NSCalendar rangeOfUnit 上的 Apple 文档:https: //developer.apple.com/documentation/foundation/nscalendar/1418344-rangeofunit
p.s looks like this uses the same logic as @Scott Means's answer, but doesn't require any category, so use which ever answer you prefer!
ps 看起来这使用与@Scott Means 的答案相同的逻辑,但不需要任何类别,因此请使用您喜欢的答案!
回答by Totte Alm
Swift 5 getting last day of month - base on different sources
Swift 5 获得每月的最后一天 - 基于不同的来源
// -------------------------------------------------------
// lastDayOfMonth
// -------------------------------------------------------
static func lastDayOfMonth(year:Int, month:Int) -> Int {
let calendar:Calendar = Calendar.current
var dc:DateComponents = DateComponents()
dc.year = year
dc.month = month + 1
dc.day = 0
let lastDateOfMonth:Date = calendar.date(from:dc)!
let lastDay = calendar.component(Calendar.Component.day, from: lastDateOfMonth)
return lastDay
}