I want to get the current week start and end date and I also want to use the previous week start and end date and next week of the start and end date in current month.
我想要得到当前周的开始日期和结束日期,我还想使用前一周的开始日期和结束日期,以及下一周的开始日期和结束日期。
Thanks in Advance.
提前谢谢。
13 个解决方案
#1
61
rangeOfUnit:startDate:interval:forDate:
. It gives you the start and the interval for a certain time unit. With it it is easy to find the start of the week in the used calendar and add the range-1 to get the latest second in that week.
rangeOfUnit:startDate可以:间隔:forDate:。它给出一个特定时间单位的开始和间隔。使用它,我们很容易在使用的日历中找到一个星期的开始,并在那个星期中添加range-1以获得最近的第二个。
NSCalendar *cal = [NSCalendar currentCalendar];
NSDate *now = [NSDate date];
NSDate *startOfTheWeek;
NSDate *endOfWeek;
NSTimeInterval interval;
[cal rangeOfUnit:NSWeekCalendarUnit
startDate:&startOfTheWeek
interval:&interval
forDate:now];
//startOfWeek holds now the first day of the week, according to locale (monday vs. sunday)
endOfWeek = [startOfTheWeek dateByAddingTimeInterval:interval-1];
// holds 23:59:59 of last day in week.
#2
19
I solve the problem thanks for Support
谢谢你的支持,我解决了这个问题
Code :- it give the current week start and end date.
代码:-它给出当前周的开始和结束日期。
NSDate *today = [NSDate date];
NSLog(@"Today date is %@",today);
dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd"];// you can use your format.
//Week Start Date
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorian components:NSWeekdayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:today];
int dayofweek = [[[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:today] weekday];// this will give you current day of week
[components setDay:([components day] - ((dayofweek) - 2))];// for beginning of the week.
NSDate *beginningOfWeek = [gregorian dateFromComponents:components];
NSDateFormatter *dateFormat_first = [[NSDateFormatter alloc] init];
[dateFormat_first setDateFormat:@"yyyy-MM-dd"];
dateString2Prev = [dateFormat stringFromDate:beginningOfWeek];
weekstartPrev = [[dateFormat_first dateFromString:dateString2Prev] retain];
NSLog(@"%@",weekstartPrev);
//Week End Date
NSCalendar *gregorianEnd = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *componentsEnd = [gregorianEnd components:NSWeekdayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:today];
int Enddayofweek = [[[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:today] weekday];// this will give you current day of week
[componentsEnd setDay:([componentsEnd day]+(7-Enddayofweek)+1)];// for end day of the week
NSDate *EndOfWeek = [gregorianEnd dateFromComponents:componentsEnd];
NSDateFormatter *dateFormat_End = [[NSDateFormatter alloc] init];
[dateFormat_End setDateFormat:@"yyyy-MM-dd"];
dateEndPrev = [dateFormat stringFromDate:EndOfWeek];
weekEndPrev = [[dateFormat_End dateFromString:dateEndPrev] retain];
NSLog(@"%@",weekEndPrev);
#3
10
A Swift version
of vikingosegundo
's answer:
vikingosegundo的回答:
let calendar = NSCalendar.currentCalendar()
var startOfTheWeek: NSDate?
var endOfWeek: NSDate!
var interval = NSTimeInterval(0)
calendar.rangeOfUnit(.WeekOfMonth, startDate: &startOfTheWeek, interval: &interval, forDate: NSDate())
endOfWeek = startOfTheWeek!.dateByAddingTimeInterval(interval - 1)
#4
10
Here is Swift 3 Version:-
以下是Swift 3版本:-
extension Date {
var startOfWeek: Date? {
let gregorian = Calendar(identifier: .gregorian)
guard let sunday = gregorian.date(from: gregorian.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self)) else { return nil }
return gregorian.date(byAdding: .day, value: 1, to: sunday)
}
var endOfWeek: Date? {
let gregorian = Calendar(identifier: .gregorian)
guard let sunday = gregorian.date(from: gregorian.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self)) else { return nil }
return gregorian.date(byAdding: .day, value: 7, to: sunday)
}
}
You can get the week start date and end date like this :
你可以得到一个星期的开始日期和结束日期如下:
let startWeek = Date().startOfWeek
let endWeek = Date().endOfWeek
print(startWeek ?? "not found start date")
print(endWeek ?? "not found end date")
#5
8
Here's an elegant way for Swift 3 (Xcode 8+):
以下是Swift 3 (Xcode 8+)的一种优雅方式:
extension Date {
var startOfWeek: Date {
let date = Calendar.current.date(from: Calendar.current.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self))!
let dslTimeOffset = NSTimeZone.local.daylightSavingTimeOffset(for: date)
return date.addingTimeInterval(dslTimeOffset)
}
var endOfWeek: Date {
return Calendar.current.date(byAdding: .second, value: 604799, to: self.startOfWeek)!
}
}
And we can use this extension like this:
我们可以这样扩展
print(Date().startOfWeek)
print(Date().endOfWeek)
#6
4
First find the current date...
首先找到当前日期…
NSDate *today = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *weekdayComponents = [gregorian components:NSWeekdayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:today];
Calcuate number of days to substract from today, in order to get the first day of the week. In this case, the first day of the week is monday. This is represented by first subtracting 0 with the weekday integer followed by adding 2 to the setDay.
计算从今天开始要减的天数,以得到一周的第一天。在这种情况下,一周的第一天是星期一。这表示为先用工作日整数减去0,然后在setDay中增加2。
Sunday = 1, Monday = 2, Tuesday = 3, Wednesday = 4, Thursday = 5, Friday = 6 and Saturday = 7. By adding more to this integers, you will go into the next week.
周日= 1,周一= 2,周二= 3,周三= 4,周四= 5,周五= 6,周六= 7。通过增加这些整数,你将进入下一周。
NSDateComponents *componentsToSubtract = [[NSDateComponents alloc] init];
[componentsToSubtract setDay: (0 - [weekdayComponents weekday]) + 2];
[componentsToSubtract setHour: 0 - [weekdayComponents hour]];
[componentsToSubtract setMinute: 0 - [weekdayComponents minute]];
[componentsToSubtract setSecond: 0 - [weekdayComponents second]];
Create date for first day in week
为每周的第一天设定日期
NSDate *beginningOfWeek = [gregorian dateByAddingComponents:componentsToSubtract toDate:today options:0];
By adding 6 to the date of the first day, we can get the last day, in our example Sunday.
通过在第一天的日期增加6,我们可以得到最后一天,在我们的示例Sunday中。
NSDateComponents *componentsToAdd = [gregorian components:NSDayCalendarUnit fromDate:beginningOfWeek];
[componentsToAdd setDay:6];
NSDate *endOfWeek = [gregorian dateByAddingComponents:componentsToAdd toDate:beginningOfWeek options:0];
for next and previous ....
下,以前....
-(IBAction)Week_CalendarActionEvents:(id)sender{
NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents *offsetComponents = [[[NSDateComponents alloc] init] autorelease];
NSDate *nextDate;
if(sender==Week_prevBarBtn) // Previous button events
[offsetComponents setDay:-7];
else if(sender==Week_nextBarBtn) // next button events
[offsetComponents setDay:7];
nextDate = [gregorian dateByAddingComponents:offsetComponents toDate:selectedDate options:0];
selectedDate = nextDate;
[selectedDate retain];
NSDateComponents *components = [gregorian components:NSWeekCalendarUnit fromDate:selectedDate];
NSInteger week = [components week];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MMMM YYYY"];
NSString *stringFromDate = [formatter stringFromDate:selectedDate];
[formatter release];
[Week_weekBarBtn setTitle:[NSString stringWithFormat:@"%@,Week %d",stringFromDate,week]];
}
#7
2
Here's some code and it also checks an edge case where the beginning of the week starts in the prior month. You can get end of week by setting setWeekday
to 7
and you can get the prior week by subtracting 1
from [components week]
这里有一些代码,它还检查了一个边缘情况,即从前一个月开始的一周。可以将setWeekday设置为7,然后从[component week]中减去1,得到上一周
// Finds the date for the first day of the week
- (NSDate *)getFirstDayOfTheWeekFromDate:(NSDate *)givenDate
{
NSCalendar *calendar = [NSCalendar currentCalendar];
// Edge case where beginning of week starts in the prior month
NSDateComponents *edgeCase = [[NSDateComponents alloc] init];
[edgeCase setMonth:2];
[edgeCase setDay:1];
[edgeCase setYear:2013];
NSDate *edgeCaseDate = [calendar dateFromComponents:edgeCase];
NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSWeekdayCalendarUnit fromDate:edgeCaseDate];
[components setWeekday:1]; // 1 == Sunday, 7 == Saturday
[components setWeek:[components week]];
NSLog(@"Edge case date is %@ and beginning of that week is %@", edgeCaseDate , [calendar dateFromComponents:components]);
// Find Sunday for the given date
components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSWeekdayCalendarUnit fromDate:givenDate];
[components setWeekday:1]; // 1 == Sunday, 7 == Saturday
[components setWeek:[components week]];
NSLog(@"Original date is %@ and beginning of week is %@", givenDate , [calendar dateFromComponents:components]);
return [calendar dateFromComponents:components];
}
#8
2
//Begining of Week Date
- (NSDate*) beginingOfWeekOfDate{
NSCalendar *tmpCalendar = [NSCalendar currentCalendar];
NSDateComponents *components = [tmpCalendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitWeekOfYear|NSCalendarUnitWeekday fromDate:self];//get the required calendar units
NSInteger weekday = tmpCalendar.firstWeekday;
components.weekday = weekday; //weekday
components.hour = 0;
components.minute = 0;
components.second = 0;
NSDate *fireDate = [tmpCalendar dateFromComponents:components];
return fireDate;
}
//End of Week Date
-(NSDate *)endOfWeekFromDate{
NSCalendar *tmpCalendar = [NSCalendar currentCalendar];
NSDateComponents *components = [tmpCalendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitWeekOfYear|NSCalendarUnitWeekday fromDate:self];//get the required calendar units
int weekday = 7; //Saturday
if (tmpCalendar.firstWeekday != 1) {
weekday = 1;
}
components.weekday = weekday;//weekday
components.hour = 23;
components.minute = 59;
components.second = 59;
NSDate *fireDate = [tmpCalendar dateFromComponents:components];
return fireDate;
}
#9
1
You can get current day and date by following code:
您可以通过以下代码获取当前的日期和日期:
NSDate *today = [NSDate date];
NSDateFormatter *dateFormat = [[[NSDateFormatter alloc] init] autorelease];
[dateFormat setDateFormat:@"EEEE"];
NSString *weekDay = [dateFormat stringFromDate:today];
[dateFormat setDateFormat:@"dd"];
NSString *thedate=[dateFormat stringFromDate:today];
//[dateFormat release];
NSLog(@"%@ %@", weekDay,thedate);
Now, You need to put some logic in it to calculate starting date and end date of the week. The logic will be such kind,
现在,您需要在其中加入一些逻辑来计算一周的开始日期和结束日期。逻辑是这样的,
if the week day is Monday
如果工作日是星期一。
then
然后
starting date = current date - 0
开始日期=当前日期- 0。
end date = current date + 6
结束日期=当前日期+ 6
and so on
等等
I think you can get the idea of it.
我想你可以理解。
#10
1
By take advantage of the method rangeOfUnit:startDate:interval:forDate:
of NSDate
, there is a simpler way to achieve this:
利用NSDate的rangeOfUnit:startDate:interval:forDate: of NSDate,有一种更简单的实现方法:
- (void)startDate:(NSDate **)start andEndDate:(NSDate **)end ofWeekOn:(NSDate *)date{
NSDate *startDate = nil;
NSTimeInterval duration = 0;
BOOL b = [[NSCalendar currentCalendar] rangeOfUnit:NSWeekCalendarUnit startDate:&startDate interval:&duration forDate:date];
if(! b){
*start = nil;
*end = nil;
return;
}
NSDate *endDate = [startDate dateByAddingTimeInterval:duration-1];
*start = startDate;
*end = endDate;
}
NSDate *this_start = nil, *this_end = nil;
[self startDate:&this_start andEndDate:&this_end ofWeekOn:[NSDate date]];
So now you have the start date and end date of this week. Then last week:
现在你有了本周的开始日期和结束日期。然后上周:
NSDate *lastWeekDate = [this_start dateByAddingTimeInterval:-10];
NSDate *last_start = nil, *last_end = nil;
[self startDate:&last_start andEndDate:&last_end ofWeekOn:lastWeekDate];
Next week:
下周:
NSDate *nextWeekDate = [this_end dateByAddingTimeInterval:10];
NSDate *next_start = nil, *next_end = nil;
[self startDate:&next_start andEndDate:&next_end ofWeekOn:nextWeekDate];
Now you have them all.
现在你拥有了它们。
#11
1
Swift 3
斯威夫特3
First find the current date...
首先找到当前日期…
let today = Date()
let gregorian = Calendar(identifier: .gregorian)
var weekdayComponents: DateComponents? = gregorian.dateComponents([.weekday], from: today)
Sunday = 1, Monday = 2, Tuesday = 3, Wednesday = 4, Thursday = 5, Friday = 6 and Saturday = 7.
周日= 1,周一= 2,周二= 3,周三= 4,周四= 5,周五= 6,周六= 7。
var componentsToSubtract = DateComponents()
componentsToSubtract.day = (0 - (weekdayComponents?.weekday!)!) + 2
beginningOfWeek = gregorian.date(byAdding: componentsToSubtract, to: today)
var componentsToAdd: DateComponents? = gregorian.dateComponents([.day], from: beginningOfWeek!)
componentsToAdd?.day = 6
endOfWeek = gregorian.date(byAdding: componentsToAdd!, to: beginningOfWeek!)
let components: DateComponents? = gregorian.dateComponents([.month], from: beginningOfWeek!)
let month: Int? = components?.month
let components1: DateComponents? = gregorian.dateComponents([.month], from: endOfWeek!)
let month1: Int? = components1?.month
print("\(month) - \(month1)")
showDate(start:beginningOfWeek!, end:endOfWeek!, strtMn:month!, endMn:month1!)
func showDate(start:Date, end:Date, strtMn:Int, endMn:Int) {
if strtMn == endMn{
let formatter = DateFormatter()
formatter.dateFormat = "MMM dd"
let stringFromDate: String = formatter.string(from: start)
let formatter1 = DateFormatter()
formatter1.dateFormat = "dd"
let stringFromDate1: String = formatter1.string(from: end)
print("\(stringFromDate) - \(stringFromDate1)")
lblDate.text = "\(stringFromDate) - \(stringFromDate1)"
}
else{
let formatter = DateFormatter()
formatter.dateFormat = "MMM dd"
let stringFromDate: String = formatter.string(from: start)
let formatter1 = DateFormatter()
formatter1.dateFormat = "MMM dd"
let stringFromDate1: String = formatter1.string(from: end)
print("\(stringFromDate) - \(stringFromDate1)")
lblDate.text = "\(stringFromDate) - \(stringFromDate1)"
}
}
for next and previous ....
下,以前....
@IBAction func week_CalendarActionEvents(_ sender: UIButton) {
let gregorian = Calendar(identifier: .gregorian)
var offsetComponents = DateComponents()
var nextStrtDate: Date?
var nextEndDate: Date?
var startDate: Date?
var endDate: Date?
startDate = beginningOfWeek
endDate = endOfWeek
if sender.tag == 1 {
offsetComponents.day = -7
}
else if sender.tag == 2 {
offsetComponents.day = 7
}
nextStrtDate = gregorian.date(byAdding: offsetComponents, to:startDate!)
startDate = nextStrtDate
beginningOfWeek = startDate
nextEndDate = gregorian.date(byAdding: offsetComponents, to: endDate!)
endDate = nextEndDate
endOfWeek = endDate
let components: DateComponents? = gregorian.dateComponents([.month], from: startDate!)
let month: Int? = components?.month
let components1: DateComponents? = gregorian.dateComponents([.month], from: endDate!)
let month1: Int? = components1?.month
print("\(month)- \(month1)")
showDate(start:startDate!, end:endDate!, strtMn:month!, endMn:month1!)
}
#12
1
Here is a solution for the swift4, we can get all the days for the current week.
这是swift4的解决方案,我们可以获得当前周的所有天数。
var calendar = Calendar(identifier: Calendar.Identifier.gregorian)
let today = calendar.startOfDay(for: Date())
let dayOfWeek = calendar.component(.weekday, from: today) - calendar.firstWeekday
let weekdays = calendar.range(of: .weekday, in: .weekOfYear, for: today)!
let days = (weekdays.lowerBound ..< weekdays.upperBound)
.flatMap { calendar.date(byAdding: .day, value: $0 - dayOfWeek, to: today) }
#13
0
In swift 3.0
在斯威夫特3.0
let cal = NSCalendar.current
//weekday
let weekday = cal.component(.weekday, from: Date())
var dateComp = cal.dateComponents([.hour, .minute, .second, .day, .month, .year], from: Date())
print(dateComp.day!)
//Start Date of the week - Sunday
dateComp.day = dateComp.day! - (weekday - 1)// start date of week
print(cal.date(from: dateComp)!)
//End Date of the Week - Saturday
dateComp = cal.dateComponents([.hour, .minute, .second, .day, .month, .year], from: Date())
dateComp.day = dateComp.day! + (7 - weekday)
print(cal.date(from: dateComp)!)
#1
61
rangeOfUnit:startDate:interval:forDate:
. It gives you the start and the interval for a certain time unit. With it it is easy to find the start of the week in the used calendar and add the range-1 to get the latest second in that week.
rangeOfUnit:startDate可以:间隔:forDate:。它给出一个特定时间单位的开始和间隔。使用它,我们很容易在使用的日历中找到一个星期的开始,并在那个星期中添加range-1以获得最近的第二个。
NSCalendar *cal = [NSCalendar currentCalendar];
NSDate *now = [NSDate date];
NSDate *startOfTheWeek;
NSDate *endOfWeek;
NSTimeInterval interval;
[cal rangeOfUnit:NSWeekCalendarUnit
startDate:&startOfTheWeek
interval:&interval
forDate:now];
//startOfWeek holds now the first day of the week, according to locale (monday vs. sunday)
endOfWeek = [startOfTheWeek dateByAddingTimeInterval:interval-1];
// holds 23:59:59 of last day in week.
#2
19
I solve the problem thanks for Support
谢谢你的支持,我解决了这个问题
Code :- it give the current week start and end date.
代码:-它给出当前周的开始和结束日期。
NSDate *today = [NSDate date];
NSLog(@"Today date is %@",today);
dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd"];// you can use your format.
//Week Start Date
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorian components:NSWeekdayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:today];
int dayofweek = [[[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:today] weekday];// this will give you current day of week
[components setDay:([components day] - ((dayofweek) - 2))];// for beginning of the week.
NSDate *beginningOfWeek = [gregorian dateFromComponents:components];
NSDateFormatter *dateFormat_first = [[NSDateFormatter alloc] init];
[dateFormat_first setDateFormat:@"yyyy-MM-dd"];
dateString2Prev = [dateFormat stringFromDate:beginningOfWeek];
weekstartPrev = [[dateFormat_first dateFromString:dateString2Prev] retain];
NSLog(@"%@",weekstartPrev);
//Week End Date
NSCalendar *gregorianEnd = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *componentsEnd = [gregorianEnd components:NSWeekdayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:today];
int Enddayofweek = [[[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:today] weekday];// this will give you current day of week
[componentsEnd setDay:([componentsEnd day]+(7-Enddayofweek)+1)];// for end day of the week
NSDate *EndOfWeek = [gregorianEnd dateFromComponents:componentsEnd];
NSDateFormatter *dateFormat_End = [[NSDateFormatter alloc] init];
[dateFormat_End setDateFormat:@"yyyy-MM-dd"];
dateEndPrev = [dateFormat stringFromDate:EndOfWeek];
weekEndPrev = [[dateFormat_End dateFromString:dateEndPrev] retain];
NSLog(@"%@",weekEndPrev);
#3
10
A Swift version
of vikingosegundo
's answer:
vikingosegundo的回答:
let calendar = NSCalendar.currentCalendar()
var startOfTheWeek: NSDate?
var endOfWeek: NSDate!
var interval = NSTimeInterval(0)
calendar.rangeOfUnit(.WeekOfMonth, startDate: &startOfTheWeek, interval: &interval, forDate: NSDate())
endOfWeek = startOfTheWeek!.dateByAddingTimeInterval(interval - 1)
#4
10
Here is Swift 3 Version:-
以下是Swift 3版本:-
extension Date {
var startOfWeek: Date? {
let gregorian = Calendar(identifier: .gregorian)
guard let sunday = gregorian.date(from: gregorian.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self)) else { return nil }
return gregorian.date(byAdding: .day, value: 1, to: sunday)
}
var endOfWeek: Date? {
let gregorian = Calendar(identifier: .gregorian)
guard let sunday = gregorian.date(from: gregorian.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self)) else { return nil }
return gregorian.date(byAdding: .day, value: 7, to: sunday)
}
}
You can get the week start date and end date like this :
你可以得到一个星期的开始日期和结束日期如下:
let startWeek = Date().startOfWeek
let endWeek = Date().endOfWeek
print(startWeek ?? "not found start date")
print(endWeek ?? "not found end date")
#5
8
Here's an elegant way for Swift 3 (Xcode 8+):
以下是Swift 3 (Xcode 8+)的一种优雅方式:
extension Date {
var startOfWeek: Date {
let date = Calendar.current.date(from: Calendar.current.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self))!
let dslTimeOffset = NSTimeZone.local.daylightSavingTimeOffset(for: date)
return date.addingTimeInterval(dslTimeOffset)
}
var endOfWeek: Date {
return Calendar.current.date(byAdding: .second, value: 604799, to: self.startOfWeek)!
}
}
And we can use this extension like this:
我们可以这样扩展
print(Date().startOfWeek)
print(Date().endOfWeek)
#6
4
First find the current date...
首先找到当前日期…
NSDate *today = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *weekdayComponents = [gregorian components:NSWeekdayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:today];
Calcuate number of days to substract from today, in order to get the first day of the week. In this case, the first day of the week is monday. This is represented by first subtracting 0 with the weekday integer followed by adding 2 to the setDay.
计算从今天开始要减的天数,以得到一周的第一天。在这种情况下,一周的第一天是星期一。这表示为先用工作日整数减去0,然后在setDay中增加2。
Sunday = 1, Monday = 2, Tuesday = 3, Wednesday = 4, Thursday = 5, Friday = 6 and Saturday = 7. By adding more to this integers, you will go into the next week.
周日= 1,周一= 2,周二= 3,周三= 4,周四= 5,周五= 6,周六= 7。通过增加这些整数,你将进入下一周。
NSDateComponents *componentsToSubtract = [[NSDateComponents alloc] init];
[componentsToSubtract setDay: (0 - [weekdayComponents weekday]) + 2];
[componentsToSubtract setHour: 0 - [weekdayComponents hour]];
[componentsToSubtract setMinute: 0 - [weekdayComponents minute]];
[componentsToSubtract setSecond: 0 - [weekdayComponents second]];
Create date for first day in week
为每周的第一天设定日期
NSDate *beginningOfWeek = [gregorian dateByAddingComponents:componentsToSubtract toDate:today options:0];
By adding 6 to the date of the first day, we can get the last day, in our example Sunday.
通过在第一天的日期增加6,我们可以得到最后一天,在我们的示例Sunday中。
NSDateComponents *componentsToAdd = [gregorian components:NSDayCalendarUnit fromDate:beginningOfWeek];
[componentsToAdd setDay:6];
NSDate *endOfWeek = [gregorian dateByAddingComponents:componentsToAdd toDate:beginningOfWeek options:0];
for next and previous ....
下,以前....
-(IBAction)Week_CalendarActionEvents:(id)sender{
NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents *offsetComponents = [[[NSDateComponents alloc] init] autorelease];
NSDate *nextDate;
if(sender==Week_prevBarBtn) // Previous button events
[offsetComponents setDay:-7];
else if(sender==Week_nextBarBtn) // next button events
[offsetComponents setDay:7];
nextDate = [gregorian dateByAddingComponents:offsetComponents toDate:selectedDate options:0];
selectedDate = nextDate;
[selectedDate retain];
NSDateComponents *components = [gregorian components:NSWeekCalendarUnit fromDate:selectedDate];
NSInteger week = [components week];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MMMM YYYY"];
NSString *stringFromDate = [formatter stringFromDate:selectedDate];
[formatter release];
[Week_weekBarBtn setTitle:[NSString stringWithFormat:@"%@,Week %d",stringFromDate,week]];
}
#7
2
Here's some code and it also checks an edge case where the beginning of the week starts in the prior month. You can get end of week by setting setWeekday
to 7
and you can get the prior week by subtracting 1
from [components week]
这里有一些代码,它还检查了一个边缘情况,即从前一个月开始的一周。可以将setWeekday设置为7,然后从[component week]中减去1,得到上一周
// Finds the date for the first day of the week
- (NSDate *)getFirstDayOfTheWeekFromDate:(NSDate *)givenDate
{
NSCalendar *calendar = [NSCalendar currentCalendar];
// Edge case where beginning of week starts in the prior month
NSDateComponents *edgeCase = [[NSDateComponents alloc] init];
[edgeCase setMonth:2];
[edgeCase setDay:1];
[edgeCase setYear:2013];
NSDate *edgeCaseDate = [calendar dateFromComponents:edgeCase];
NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSWeekdayCalendarUnit fromDate:edgeCaseDate];
[components setWeekday:1]; // 1 == Sunday, 7 == Saturday
[components setWeek:[components week]];
NSLog(@"Edge case date is %@ and beginning of that week is %@", edgeCaseDate , [calendar dateFromComponents:components]);
// Find Sunday for the given date
components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSWeekdayCalendarUnit fromDate:givenDate];
[components setWeekday:1]; // 1 == Sunday, 7 == Saturday
[components setWeek:[components week]];
NSLog(@"Original date is %@ and beginning of week is %@", givenDate , [calendar dateFromComponents:components]);
return [calendar dateFromComponents:components];
}
#8
2
//Begining of Week Date
- (NSDate*) beginingOfWeekOfDate{
NSCalendar *tmpCalendar = [NSCalendar currentCalendar];
NSDateComponents *components = [tmpCalendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitWeekOfYear|NSCalendarUnitWeekday fromDate:self];//get the required calendar units
NSInteger weekday = tmpCalendar.firstWeekday;
components.weekday = weekday; //weekday
components.hour = 0;
components.minute = 0;
components.second = 0;
NSDate *fireDate = [tmpCalendar dateFromComponents:components];
return fireDate;
}
//End of Week Date
-(NSDate *)endOfWeekFromDate{
NSCalendar *tmpCalendar = [NSCalendar currentCalendar];
NSDateComponents *components = [tmpCalendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitWeekOfYear|NSCalendarUnitWeekday fromDate:self];//get the required calendar units
int weekday = 7; //Saturday
if (tmpCalendar.firstWeekday != 1) {
weekday = 1;
}
components.weekday = weekday;//weekday
components.hour = 23;
components.minute = 59;
components.second = 59;
NSDate *fireDate = [tmpCalendar dateFromComponents:components];
return fireDate;
}
#9
1
You can get current day and date by following code:
您可以通过以下代码获取当前的日期和日期:
NSDate *today = [NSDate date];
NSDateFormatter *dateFormat = [[[NSDateFormatter alloc] init] autorelease];
[dateFormat setDateFormat:@"EEEE"];
NSString *weekDay = [dateFormat stringFromDate:today];
[dateFormat setDateFormat:@"dd"];
NSString *thedate=[dateFormat stringFromDate:today];
//[dateFormat release];
NSLog(@"%@ %@", weekDay,thedate);
Now, You need to put some logic in it to calculate starting date and end date of the week. The logic will be such kind,
现在,您需要在其中加入一些逻辑来计算一周的开始日期和结束日期。逻辑是这样的,
if the week day is Monday
如果工作日是星期一。
then
然后
starting date = current date - 0
开始日期=当前日期- 0。
end date = current date + 6
结束日期=当前日期+ 6
and so on
等等
I think you can get the idea of it.
我想你可以理解。
#10
1
By take advantage of the method rangeOfUnit:startDate:interval:forDate:
of NSDate
, there is a simpler way to achieve this:
利用NSDate的rangeOfUnit:startDate:interval:forDate: of NSDate,有一种更简单的实现方法:
- (void)startDate:(NSDate **)start andEndDate:(NSDate **)end ofWeekOn:(NSDate *)date{
NSDate *startDate = nil;
NSTimeInterval duration = 0;
BOOL b = [[NSCalendar currentCalendar] rangeOfUnit:NSWeekCalendarUnit startDate:&startDate interval:&duration forDate:date];
if(! b){
*start = nil;
*end = nil;
return;
}
NSDate *endDate = [startDate dateByAddingTimeInterval:duration-1];
*start = startDate;
*end = endDate;
}
NSDate *this_start = nil, *this_end = nil;
[self startDate:&this_start andEndDate:&this_end ofWeekOn:[NSDate date]];
So now you have the start date and end date of this week. Then last week:
现在你有了本周的开始日期和结束日期。然后上周:
NSDate *lastWeekDate = [this_start dateByAddingTimeInterval:-10];
NSDate *last_start = nil, *last_end = nil;
[self startDate:&last_start andEndDate:&last_end ofWeekOn:lastWeekDate];
Next week:
下周:
NSDate *nextWeekDate = [this_end dateByAddingTimeInterval:10];
NSDate *next_start = nil, *next_end = nil;
[self startDate:&next_start andEndDate:&next_end ofWeekOn:nextWeekDate];
Now you have them all.
现在你拥有了它们。
#11
1
Swift 3
斯威夫特3
First find the current date...
首先找到当前日期…
let today = Date()
let gregorian = Calendar(identifier: .gregorian)
var weekdayComponents: DateComponents? = gregorian.dateComponents([.weekday], from: today)
Sunday = 1, Monday = 2, Tuesday = 3, Wednesday = 4, Thursday = 5, Friday = 6 and Saturday = 7.
周日= 1,周一= 2,周二= 3,周三= 4,周四= 5,周五= 6,周六= 7。
var componentsToSubtract = DateComponents()
componentsToSubtract.day = (0 - (weekdayComponents?.weekday!)!) + 2
beginningOfWeek = gregorian.date(byAdding: componentsToSubtract, to: today)
var componentsToAdd: DateComponents? = gregorian.dateComponents([.day], from: beginningOfWeek!)
componentsToAdd?.day = 6
endOfWeek = gregorian.date(byAdding: componentsToAdd!, to: beginningOfWeek!)
let components: DateComponents? = gregorian.dateComponents([.month], from: beginningOfWeek!)
let month: Int? = components?.month
let components1: DateComponents? = gregorian.dateComponents([.month], from: endOfWeek!)
let month1: Int? = components1?.month
print("\(month) - \(month1)")
showDate(start:beginningOfWeek!, end:endOfWeek!, strtMn:month!, endMn:month1!)
func showDate(start:Date, end:Date, strtMn:Int, endMn:Int) {
if strtMn == endMn{
let formatter = DateFormatter()
formatter.dateFormat = "MMM dd"
let stringFromDate: String = formatter.string(from: start)
let formatter1 = DateFormatter()
formatter1.dateFormat = "dd"
let stringFromDate1: String = formatter1.string(from: end)
print("\(stringFromDate) - \(stringFromDate1)")
lblDate.text = "\(stringFromDate) - \(stringFromDate1)"
}
else{
let formatter = DateFormatter()
formatter.dateFormat = "MMM dd"
let stringFromDate: String = formatter.string(from: start)
let formatter1 = DateFormatter()
formatter1.dateFormat = "MMM dd"
let stringFromDate1: String = formatter1.string(from: end)
print("\(stringFromDate) - \(stringFromDate1)")
lblDate.text = "\(stringFromDate) - \(stringFromDate1)"
}
}
for next and previous ....
下,以前....
@IBAction func week_CalendarActionEvents(_ sender: UIButton) {
let gregorian = Calendar(identifier: .gregorian)
var offsetComponents = DateComponents()
var nextStrtDate: Date?
var nextEndDate: Date?
var startDate: Date?
var endDate: Date?
startDate = beginningOfWeek
endDate = endOfWeek
if sender.tag == 1 {
offsetComponents.day = -7
}
else if sender.tag == 2 {
offsetComponents.day = 7
}
nextStrtDate = gregorian.date(byAdding: offsetComponents, to:startDate!)
startDate = nextStrtDate
beginningOfWeek = startDate
nextEndDate = gregorian.date(byAdding: offsetComponents, to: endDate!)
endDate = nextEndDate
endOfWeek = endDate
let components: DateComponents? = gregorian.dateComponents([.month], from: startDate!)
let month: Int? = components?.month
let components1: DateComponents? = gregorian.dateComponents([.month], from: endDate!)
let month1: Int? = components1?.month
print("\(month)- \(month1)")
showDate(start:startDate!, end:endDate!, strtMn:month!, endMn:month1!)
}
#12
1
Here is a solution for the swift4, we can get all the days for the current week.
这是swift4的解决方案,我们可以获得当前周的所有天数。
var calendar = Calendar(identifier: Calendar.Identifier.gregorian)
let today = calendar.startOfDay(for: Date())
let dayOfWeek = calendar.component(.weekday, from: today) - calendar.firstWeekday
let weekdays = calendar.range(of: .weekday, in: .weekOfYear, for: today)!
let days = (weekdays.lowerBound ..< weekdays.upperBound)
.flatMap { calendar.date(byAdding: .day, value: $0 - dayOfWeek, to: today) }
#13
0
In swift 3.0
在斯威夫特3.0
let cal = NSCalendar.current
//weekday
let weekday = cal.component(.weekday, from: Date())
var dateComp = cal.dateComponents([.hour, .minute, .second, .day, .month, .year], from: Date())
print(dateComp.day!)
//Start Date of the week - Sunday
dateComp.day = dateComp.day! - (weekday - 1)// start date of week
print(cal.date(from: dateComp)!)
//End Date of the Week - Saturday
dateComp = cal.dateComponents([.hour, .minute, .second, .day, .month, .year], from: Date())
dateComp.day = dateComp.day! + (7 - weekday)
print(cal.date(from: dateComp)!)