40

今週の開始日と終了日を取得したいのですが、前週の開始日と終了日、および当月の開始日と終了日の翌週も使用したいと思います。

前もって感謝します。

4

18 に答える 18

66

rangeOfUnit:startDate:interval:forDate:。それはあなたに特定の時間単位の開始と間隔を与えます。これを使用すると、使用済みのカレンダーで週の始まりを簡単に見つけ、範囲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.
于 2013-06-07T21:22:44.950 に答える
21

サポートのおかげで問題を解決します

コード:-現在の週の開始日と終了日を示します。

 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);
于 2012-07-30T06:50:22.137 に答える
16

これがSwift3バージョンです:-

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

週の開始日と終了日は次のように取得できます。

let startWeek = Date().startOfWeek
let endWeek = Date().endOfWeek

print(startWeek ?? "not found start date")
print(endWeek ?? "not found end date") 
于 2017-06-30T13:16:48.737 に答える
11

Swiftバージョン

答え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)
于 2015-12-03T21:35:02.163 に答える
9

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)!
    }
}

そして、この拡張機能を次のように使用できます。

print(Date().startOfWeek)
print(Date().endOfWeek)
于 2016-11-08T01:33:15.273 に答える
6

Swift4ソリューション

私は自分の要件に従って理解しました、そこで私は以下の日付を見つけました。

1. Today

2. Tomorrow 

3. This Week 

4. This Weekend 

5. Next Week 

6. Next Weekend

だから、私は今週来週Date Extensionの日付を取得するために作成しました。

コード

extension Date {

    func getWeekDates() -> (thisWeek:[Date],nextWeek:[Date]) {
        var tuple: (thisWeek:[Date],nextWeek:[Date])
        var arrThisWeek: [Date] = []
        for i in 0..<7 {
            arrThisWeek.append(Calendar.current.date(byAdding: .day, value: i, to: startOfWeek)!)
        }
        var arrNextWeek: [Date] = []
        for i in 1...7 {
            arrNextWeek.append(Calendar.current.date(byAdding: .day, value: i, to: arrThisWeek.last!)!)
        }
        tuple = (thisWeek: arrThisWeek,nextWeek: arrNextWeek)
        return tuple
    }

    var tomorrow: Date {
        return Calendar.current.date(byAdding: .day, value: 1, to: noon)!
    }
    var noon: Date {
        return Calendar.current.date(bySettingHour: 12, minute: 0, second: 0, of: self)!
    }

    var startOfWeek: Date {
        let gregorian = Calendar(identifier: .gregorian)
        let sunday = gregorian.date(from: gregorian.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self))
        return gregorian.date(byAdding: .day, value: 1, to: sunday!)!
    }

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

利用方法:

let arrWeekDates = Date().getWeekDates() // Get dates of Current and Next week.
let dateFormat = "MMM dd" // Date format
let thisMon = arrWeekDates.thisWeek.first!.toDate(format: dateFormat)
let thisSat = arrWeekDates.thisWeek[arrWeekDates.thisWeek.count - 2].toDate(format: dateFormat)
let thisSun = arrWeekDates.thisWeek[arrWeekDates.thisWeek.count - 1].toDate(format: dateFormat)

let nextMon = arrWeekDates.nextWeek.first!.toDate(format: dateFormat)
let nextSat = arrWeekDates.nextWeek[arrWeekDates.nextWeek.count - 2].toDate(format: dateFormat)
let nextSun = arrWeekDates.nextWeek[arrWeekDates.nextWeek.count - 1].toDate(format: dateFormat)

print("Today: \(Date().toDate(format: dateFormat))") // Sep 26
print("Tomorrow: \(Date().tomorrow.toDate(format: dateFormat))") // Sep 27
print("This Week: \(thisMon) - \(thisSun)") // Sep 24 - Sep 30
print("This Weekend: \(thisSat) - \(thisSun)") // Sep 29 - Sep 30
print("Next Week: \(nextMon) - \(nextSun)") // Oct 01 - Oct 07
print("Next Weekend: \(nextSat) - \(nextSun)") // Oct 06 - Oct 07

必要に応じて変更できExtensionます。

ありがとう!

于 2018-09-26T07:17:20.357 に答える
4

最初に現在の日付を見つけます...

NSDate *today = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *weekdayComponents     = [gregorian components:NSWeekdayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:today];

週の最初の日を取得するために、今日から差し引く日数を計算します。この場合、週の最初の日は月曜日です。これは、最初に平日の整数で0を減算し、次にsetDayに2を加算することで表されます。

日曜日=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]];

週の最初の日の日付を作成します

NSDate *beginningOfWeek = [gregorian dateByAddingComponents:componentsToSubtract toDate:today options:0];

初日の日付に6を加えると、最終日、この例では日曜日を取得できます。

NSDateComponents *componentsToAdd = [gregorian components:NSDayCalendarUnit fromDate:beginningOfWeek];
[componentsToAdd setDay:6];
NSDate *endOfWeek = [gregorian dateByAddingComponents:componentsToAdd toDate:beginningOfWeek options:0];

次と前のために...。

-(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]];
}
于 2012-07-27T05:55:43.313 に答える
3

これが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) }
于 2018-01-23T10:03:03.403 に答える
2

ここにいくつかのコードがあり、週の初めが前の月に始まるエッジケースもチェックします。に設定setWeekdayすることで週末を取得でき、から7減算することで前の週を取得できます。1[components week]

// 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];
}
于 2013-02-04T14:29:52.630 に答える
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;
}
于 2016-08-23T12:54:39.943 に答える
2

Swift5.xのソリューション

日付拡張の作成:

func weekPeriod() -> (startDate: Date, endDate: Date) {
    let calendar = Calendar(identifier: .gregorian)
    guard let sundayDate = calendar.date(from: calendar.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self)) else { return (startDate: Date(), endDate: Date()) }
    
    if calendar.isDateInToday(sundayDate) {
        let startDate = calendar.date(byAdding: .day, value: -6, to: sundayDate) ?? Date()
        let endDate = sundayDate
        return (startDate: startDate, endDate: endDate)
    }
    
    let startDate = calendar.date(byAdding: .day, value: 1, to: sundayDate) ?? Date()
    let endDate = calendar.date(byAdding: .day, value: 6, to: startDate) ?? Date()
    
    return (startDate: startDate, endDate: endDate)
}
于 2021-04-08T18:43:20.450 に答える
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

end date = current date + 6

and so on

I think you can get the idea of it.

于 2012-07-27T05:32:29.233 に答える
1

rangeOfUnit:startDate:interval:forDate:の方法を利用することにより、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]];

これで、今週の開始日と終了日がわかりました。それから先週:

NSDate *lastWeekDate = [this_start dateByAddingTimeInterval:-10];
NSDate *last_start = nil, *last_end = nil;
[self startDate:&last_start andEndDate:&last_end ofWeekOn:lastWeekDate];

次の週:

NSDate *nextWeekDate = [this_end dateByAddingTimeInterval:10];
NSDate *next_start = nil, *next_end = nil;
[self startDate:&next_start andEndDate:&next_end ofWeekOn:nextWeekDate];

今、あなたはそれらすべてを持っています。

于 2013-05-05T07:22:25.157 に答える
1

スウィフト3

最初に現在の日付を見つけます...

    let today = Date()
    let gregorian = Calendar(identifier: .gregorian)
    var weekdayComponents: DateComponents? = gregorian.dateComponents([.weekday], from: today)

日曜日=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)"
    }
}

次と前のために...。

@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!)
}
于 2017-05-03T07:53:21.360 に答える
1

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

    var yesterdayDate: Date? {
        return NSCalendar.current.date(byAdding: .day, value: -1, to: noon)!
    }

    var tommorowDate: Date? {
        return NSCalendar.current.date(byAdding: .day, value: 1, to: noon)!
    }

    var previousDate: Date? {
        let oneDay:Double = 60 * 60 * 24
        return self.addingTimeInterval(-(Double(oneDay)))
    }

    var nextDate: Date? {
        let oneDay:Double = 60 * 60 * 24
        return self.addingTimeInterval(oneDay)
    }

    var noon: Date {
        return NSCalendar.current.date(bySettingHour: 12, minute: 0, second: 0, of: self)!
    }

    var month: Int {
        return Calendar.current.component(.month,  from: self)
    }
}
于 2018-10-22T09:59:34.010 に答える
1

Swift 4.2

現在の週の日付を表示したい場合は、ここにコードがあります。

  override func viewDidLoad() {
        super.viewDidLoad()

        for dateIndex in 0..<7 {
            guard let startWeek = Date().startOfWeek else { return }
            let date = Calendar.current.date(byAdding: .day, value: dateIndex + 1, to: startWeek)
            print(date)
        }

}



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

于 2019-06-25T09:27:34.727 に答える
0

swift3.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)!)
于 2017-05-09T12:46:09.310 に答える
0
  • どの地域からでも、週に3つのステップがありますStart dateEnd date
  1. 当日の曜日を検索します。
func getTodayWeekDay() -> String {
       let dateFormatter = DateFormatter()
       dateFormatter.dateFormat = "EEEE"
       let weekDay = dateFormatter.string(from: Date())
       return weekDay
}
  1. 何日もの間、 emunクラスを作成subtractionadditionます。

つまり、現在の曜日が現在の週をWednesday取得するためのものである場合、現在の日Mondayから減算する必要があり-2ます。そしてSunday、現在の週を取得するには、現在の日に追加する必要があり4ます。

enum WeekDays: String {
    case monday = "Monday"
    case tuesday = "Tuesday"
    case wednesday = "Wednesday"
    case thursday = "Thursday"
    case friday = "Friday"
    case saturday = "Saturday"
    case sunday = "Sunday"
    
    var daysToSubstract: Int {
        switch self {
        case .monday: return 0
        case .tuesday: return -1
        case .wednesday: return -2
        case .thursday: return -3
        case .friday: return -4
        case .saturday: return -5
        case .sunday: return -6
        }
    }
    
    var daysToAdd: Int {
        switch self {
        case .monday: return 6
        case .tuesday: return 5
        case .wednesday: return 4
        case .thursday: return 3
        case .friday: return 2
        case .saturday: return 1
        case .sunday: return 0
        }
    }
}

  1. 現在の日から取得しますStart-weekEnd-weeksubtractionaddition
extension Date {
    var startOfWeek: String? {
        let gregorian = Calendar(identifier: .gregorian)
        let startWeek = dateFormatter.string(from:gregorian.date(byAdding: .day, value: WeekDays(rawValue: getTodayWeekDay())?.daysToSubstract ?? 0, to: self)!)
        print("start-week--- \(startWeek)")
        return startWeek
    }

    var endOfWeek: String? {
        let gregorian = Calendar(identifier: .gregorian)
        let endWeek = dateFormatter.string(from:gregorian.date(byAdding: .day, value: WeekDays(rawValue: getTodayWeekDay())?.daysToAdd ?? 6, to: self)!)
        print("end-week--- \(endWeek)")
        return endWeek
    }
}
  • 以下のような機能を使用できます。
Date().startOfWeek
Date().endOfWeek
于 2021-12-18T13:56:45.373 に答える