如何在Swift中更改一周的第一天

时间:2015-03-26 14:34:45

标签: ios date swift

我制作了一个功能正常的应用,其中一部分包括从日期选择器格式化日期。

我需要更改一周的第一天,因为工作日显示为" 1" - " 7"。但是,第1天目前是星期日,我需要第1天为星期一和星期日为第7天。

我的日期格式化程序和选择器的代码如下:

var chosenDate = self.datePicker.date
var formatter = NSDateFormatter()        
formatter.dateFormat = "ewYY"

let day = formatter.stringFromDate(chosenDate)
let dateResult = "\(day)"

DestViewController.date = dateResult

我从此页面获得了所有日期格式信息:

http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns

我似乎无法弄清楚如何改变一周的第一天?

非常感谢提前 标记

1 个答案:

答案 0 :(得分:0)

以下是如何在swift中操作日期的好例子。您可以更改代码以更好地满足您的需求,但现在它可以满足您的需求。

// Playground - noun: a place where people can play

// Setup the calendar object
let calendar = NSCalendar.currentCalendar()

// Set up date object
let date = NSDate()
// Create an NSDate for the first and last day of the month
let components = NSCalendar.currentCalendar().components(NSCalendarUnit.CalendarUnitMonth, fromDate: date)


components.month

// Getting the First and Last date of the month
components.day = 1
let firstDateOfMonth: NSDate = calendar.dateFromComponents(components)!

components.month  += 1
components.day     = 0
let lastDateOfMonth: NSDate = calendar.dateFromComponents(components)!

var unitFlags = NSCalendarUnit.WeekOfMonthCalendarUnit |
    NSCalendarUnit.WeekdayCalendarUnit     |
    NSCalendarUnit.CalendarUnitDay

let firstDateComponents = calendar.components(unitFlags, fromDate: firstDateOfMonth)
let lastDateComponents  = calendar.components(unitFlags, fromDate: lastDateOfMonth)

// Sun = 1, Sat = 7
let firstWeek = firstDateComponents.weekOfMonth
let lastWeek  = lastDateComponents.weekOfMonth

let numOfDatesToPrepend = firstDateComponents.weekday - 1
let numOfDatesToAppend  = 7 - lastDateComponents.weekday + (6 - lastDateComponents.weekOfMonth) * 7

let startDate: NSDate = calendar.dateByAddingUnit(NSCalendarUnit.CalendarUnitDay, value: -numOfDatesToPrepend, toDate: firstDateOfMonth, options: nil)!
let endDate:   NSDate = calendar.dateByAddingUnit(NSCalendarUnit.CalendarUnitDay, value: numOfDatesToAppend, toDate: lastDateOfMonth, options: nil)!

Array(map(0..<42) {
    calendar.dateByAddingUnit(NSCalendarUnit.CalendarUnitDay, value: $0, toDate: startDate, options: nil)!
    })

"\(components.year)"


//var dateString = stringFromDate(NSDate())// change to your date format
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "EE"
var dateString = dateFormatter.stringFromDate(NSDate())
var xdate = dateFormatter.dateFromString(dateString)
//var someDate = dateFormatter.dateString
println(dateString)

这将输出::

"Thu"