Saya membuat metode yang seharusnya mengambil string dalam bentuk "YYYY-MM-DD" dan mengeluarkan int yang mewakili posisi tanggal dalam kaitannya dengan minggu itu (terlepas apakah itu tumpang tindih antara bulan). Jadi misal hari minggu = 1 senin = 2 dan seterusnya.
Ini kode saya:
func getDayOfWeek(today:String)->Int{
var formatter:NSDateFormatter = NSDateFormatter()
formatter.dateFormat = "YYYY-MM-DD"
var todayDate:NSDate = formatter.dateFromString(today)!
var myCalendar:NSCalendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)
var myComponents = myCalendar.components(NSCalendarUnit.WeekdayOrdinalCalendarUnit, fromDate: todayDate)
var weekDay = myComponents.weekdayOrdinal
return weekDay
}
Saya tahu itu NSCalendarUnit.WeekdayOrdinalCalendar
salah tetapi saya telah mencoba menurut saya kombinasi yang paling logis. Dan juga telah dipusingkan dengan myComponents.weekdayOrdinal
misal bekas mycomponents.day
atau .weekday
.
Berikut adalah opsi saya tentang apa yang harus digunakan:
static var EraCalendarUnit: NSCalendarUnit { get }
static var YearCalendarUnit: NSCalendarUnit { get }
static var MonthCalendarUnit: NSCalendarUnit { get }
static var DayCalendarUnit: NSCalendarUnit { get }
static var HourCalendarUnit: NSCalendarUnit { get }
static var MinuteCalendarUnit: NSCalendarUnit { get }
static var SecondCalendarUnit: NSCalendarUnit { get }
static var WeekCalendarUnit: NSCalendarUnit { get }
static var WeekdayCalendarUnit: NSCalendarUnit { get }
static var WeekdayOrdinalCalendarUnit: NSCalendarUnit { get }
static var QuarterCalendarUnit: NSCalendarUnit { get }
static var WeekOfMonthCalendarUnit: NSCalendarUnit { get }
static var WeekOfYearCalendarUnit: NSCalendarUnit { get }
static var YearForWeekOfYearCalendarUnit: NSCalendarUnit { get }
static var CalendarCalendarUnit: NSCalendarUnit { get }
static var TimeZoneCalendarUnit: NSCalendarUnit { get }
Tidak jelas bagi saya karena tidak ada opsi DayOfWeekUnit (atau yang serupa).
swift
nsdate
nscalendar
boidkan
sumber
sumber
Jawaban:
Apa yang Anda cari (jika saya memahami pertanyaannya dengan benar) adalah
NSCalendarUnit.CalendarUnitWeekday
. Properti terkait dariNSDateComponents
adalahweekday
.Perhatikan juga bahwa format tanggal Anda salah (spesifikasi lengkap dapat ditemukan di sini: http://unicode.org/reports/tr35/tr35-6.html ).
Fungsi ini dapat sedikit disederhanakan, menggunakan inferensi tipe otomatis, Anda juga menggunakan banyak variabel di mana konstanta cukup. Selain itu, fungsi tersebut harus mengembalikan opsional
nil
untuk string masukan yang tidak valid.Kode yang diperbarui untuk Swift 3 dan yang lebih baru:
func getDayOfWeek(_ today:String) -> Int? { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd" guard let todayDate = formatter.date(from: today) else { return nil } let myCalendar = Calendar(identifier: .gregorian) let weekDay = myCalendar.component(.weekday, from: todayDate) return weekDay }
Contoh:
if let weekday = getDayOfWeek("2014-08-27") { print(weekday) } else { print("bad input") }
Jawaban asli untuk Swift 2:
func getDayOfWeek(today:String)->Int? { let formatter = NSDateFormatter() formatter.dateFormat = "yyyy-MM-dd" if let todayDate = formatter.dateFromString(today) { let myCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)! let myComponents = myCalendar.components(.Weekday, fromDate: todayDate) let weekDay = myComponents.weekday return weekDay } else { return nil } }
sumber
func getDayOfWeek(today:String)->Int?
. Jika Anda memaksa membuka opsional itu masih macet, bukan?if let ...
bekerja juga dengan opsional yang tidak terbungkus secara implisit.Cepat 3 & 4
Mengambil nomor hari dalam seminggu secara dramatis disederhanakan di Swift 3 karena
DateComponents
tidak lagi opsional. Ini dia sebagai perpanjangan:extension Date { func dayNumberOfWeek() -> Int? { return Calendar.current.dateComponents([.weekday], from: self).weekday } } // returns an integer from 1 - 7, with 1 being Sunday and 7 being Saturday print(Date().dayNumberOfWeek()!) // 4
Jika Anda mencari versi tertulis, yang dilokalkan pada hari itu:
extension Date { func dayOfWeek() -> String? { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "EEEE" return dateFormatter.string(from: self).capitalized // or use capitalized(with: locale) if you want } } print(Date().dayOfWeek()!) // Wednesday
sumber
Jika Anda ingin "Minggu" penuh, "Senin", "Selasa", "Rabu", dll.
EDIT: Sebenarnya ada format bawaan yang mengembalikan nama hari yang dilokalkan:
extension NSDate { func dayOfTheWeek() -> String? { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "EEEE" return dateFormatter.stringFromDate(self) } }
Solusi saya sebelumnya (hanya untuk bahasa Inggris):
extension NSDate { func dayOfTheWeek() -> String? { let weekdays = [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ] let calendar: NSCalendar = NSCalendar.currentCalendar() let components: NSDateComponents = calendar.components(.Weekday, fromDate: self) return weekdays[components.weekday - 1] } }
Anda tidak perlu membuka kalender dan komponen, semuanya dijamin oleh framework yayasan.
Pemakaian:
print(myDate.dayOfTheWeek())
sumber
Jawaban sederhananya (swift 3):
Calendar.current.component(.weekday, from: Date())
sumber
Dalam kasus saya, saya mencari untaian tiga huruf untuk setiap hari. Saya memodifikasi fungsi @Martin R sebagai berikut:
func getDayOfWeekString(today:String)->String? { let formatter = NSDateFormatter() formatter.dateFormat = "yyyy-MM-dd" if let todayDate = formatter.dateFromString(today) { let myCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)! let myComponents = myCalendar.components(.Weekday, fromDate: todayDate) let weekDay = myComponents.weekday switch weekDay { case 1: return "Sun" case 2: return "Mon" case 3: return "Tue" case 4: return "Wed" case 5: return "Thu" case 6: return "Fri" case 7: return "Sat" default: print("Error fetching days") return "Day" } } else { return nil } }
sumber
dateFormat
Ada cara yang lebih mudah. Cukup berikan tanggal string Anda ke fungsi berikut, itu akan memberi Anda nama hari :)
func getDayNameBy(stringDate: String) -> String { let df = NSDateFormatter() df.dateFormat = "YYYY-MM-dd" let date = df.dateFromString(stringDate)! df.dateFormat = "EEEE" return df.stringFromDate(date); }
sumber
extension Date { var weekdayName: String { let formatter = DateFormatter(); formatter.dateFormat = "E" return formatter.string(from: self as Date) } var weekdayNameFull: String { let formatter = DateFormatter(); formatter.dateFormat = "EEEE" return formatter.string(from: self as Date) } var monthName: String { let formatter = DateFormatter(); formatter.dateFormat = "MMM" return formatter.string(from: self as Date) } var OnlyYear: String { let formatter = DateFormatter(); formatter.dateFormat = "YYYY" return formatter.string(from: self as Date) } var period: String { let formatter = DateFormatter(); formatter.dateFormat = "a" return formatter.string(from: self as Date) } var timeOnly: String { let formatter = DateFormatter(); formatter.dateFormat = "hh : mm" return formatter.string(from: self as Date) } var timeWithPeriod: String { let formatter = DateFormatter(); formatter.dateFormat = "hh : mm a" return formatter.string(from: self as Date) } var DatewithMonth: String { let formatter = DateFormatter(); formatter.dateStyle = .medium ; return formatter.string(from: self as Date) } }
penggunaan biarkan weekday = Date (). weekdayName
sumber
Perpanjangan tanggal Swift 3
extension Date { var weekdayOrdinal: Int { return Calendar.current.component(.weekday, from: self) } }
sumber
Anda dapat menggunakan tabel date_formats untuk mengonversi tanggal Anda ke format yang berbeda. Kode terpendek saya:
func getDayOfWeek(today: String) -> Int{ let formatter:NSDateFormatter = NSDateFormatter() formatter.dateFormat = "yyyy-MM-dd" let todayDate = formatter.dateFromString(today) formatter.dateFormat = "e" // "eeee" -> Friday let weekDay = formatter.stringFromDate(todayDate!) return Int(weekDay)! } getDayOfWeek("2015-12-18") // 6
sumber
SWIFT 5 - Hari dalam seminggu
extension Date { var dayofTheWeek: String { let dayNumber = Calendar.current.component(.weekday, from: self) // day number starts from 1 but array count from 0 return daysOfTheWeek[dayNumber - 1] } private var daysOfTheWeek: [String] { return ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] } }
Perpanjangan tanggal berdasarkan jawaban Fattie
sumber
Solusi praktis ...
Ketahuilah bahwa hasil adalah bilangan bulat satu sampai tujuh.
(Bukan nol sampai enam.)
let trivialDayStringsORDINAL = ["", "SUN","MON","TUE","WED","THU","FRI","SAT"] // note that zero is not used
lalu ...
let dow = Calendar.current.component(.weekday, from: someDate) print( trivialDayStringsORDINAL[dow] )
sumber
Sudah ada banyak jawaban di sini tapi saya pikir ada cara lain, mungkin lebih baik, untuk melakukan ini dengan menggunakan yang benar
Calendar
API yang .Saya menyarankan agar hari dalam seminggu menggunakan
weekdaySymbols
propertiCalendar
( docs ) dalam ekstensi untukDate
:extension Date { /// Returns the day of the week as a `String`, e.g. "Monday" var dayOfWeek: String { let calendar = Calendar.autoupdatingCurrent return calendar.weekdaySymbols[calendar.component(.weekday, from: self) - 1] } }
Ini membutuhkan inisialisasi yang
Date
pertama, yang akan saya lakukan dengan menggunakan customDateFormatter
:extension DateFormatter { /// returns a `DateFormatter` with the format "yyyy-MM-dd". static var standardDate: DateFormatter { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd" return formatter } }
Ini kemudian dapat dipanggil dengan:
DateFormatter.standardDate.date(from: "2018-09-18")!.dayOfWeek
Mengapa saya lebih suka ini:
dayOfWeek
tidak harus peduli dengan zona waktu karena kalender pengguna digunakan, beberapa solusi lain di sini akan menampilkan hari yang salah karena zona waktu tidak dipertimbangkan.DateFormatter
dan menggunakannya sebagai gantinya?weekdaySymbols
dilokalkan untuk Anda.weekDaySymbols
dapat diganti dengan opsi lain sepertishortWeekdaySymbols
"Sen", "Sel", dll.Harap diperhatikan: Contoh ini
DateFormatter
juga tidak mempertimbangkan zona waktu atau lokal, Anda harus mengaturnya sesuai kebutuhan. Jika tanggalnya selalu tepat, pertimbangkan untuk menyetel zona waktuTimeZone(secondsFromGMT: 0)
.sumber
weekdaySymbols
, terima kasihSaya akhirnya membutuhkan beberapa string lagi dari tanggal tersebut, termasuk tanggal dalam seminggu (misalnya "5") dan bulan dalam setahun (misalnya Agustus). Di bawah ini adalah ketiga fungsi yang telah saya buat berdasarkan fungsi @Martin R dan dimodifikasi untuk mengembalikan 3 string karakter:
//Date String Helper Functions func getDayOfWeek(today:String)->String? { let formatter = NSDateFormatter() formatter.dateFormat = "yyyy-MM-dd" if let todayDate = formatter.dateFromString(today) { let myCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)! let myComponents = myCalendar.components(.Weekday, fromDate: todayDate) let weekDay = myComponents.weekday switch weekDay { case 1: return "Sun" case 2: return "Mon" case 3: return "Tue" case 4: return "Wed" case 5: return "Thu" case 6: return "Fri" case 7: return "Sat" default: print("Error fetching days") return "Day" } } else { return nil } } func getDateOfMonth(today:String)->String? { let formatter = NSDateFormatter() formatter.dateFormat = "yyyy-MM-dd" if let todayDate = formatter.dateFromString(today) { let myCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)! let myComponents = myCalendar.components(.Day, fromDate: todayDate) let weekDay = myComponents.day switch weekDay { case 1: return "1st" case 2: return "2nd" case 3: return "3rd" case 4: return "4th" case 5: return "5th" case 6: return "6th" case 7: return "7th" case 8: return "8th" case 9: return "9th" case 10: return "10th" case 11: return "11th" case 12: return "12th" case 13: return "13th" case 14: return "14th" case 15: return "15th" case 16: return "16th" case 17: return "17th" case 18: return "18th" case 19: return "19th" case 20: return "20th" case 21: return "21st" case 22: return "22nd" case 23: return "23rd" case 24: return "24th" case 25: return "25th" case 26: return "26th" case 27: return "27th" case 28: return "28th" case 29: return "29th" case 30: return "30th" case 31: return "31st" default: print("Error fetching Date Of Month") return "Day" } } else { return nil } } func getMonthOfYear(today:String)->String? { let formatter = NSDateFormatter() formatter.dateFormat = "yyyy-MM-dd" if let todayDate = formatter.dateFromString(today) { let myCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)! let myComponents = myCalendar.components(.Month, fromDate: todayDate) let month = myComponents.month switch month { case 1: return "Jan" case 2: return "Feb" case 3: return "Mar" case 4: return "Apr" case 5: return "May" case 6: return "Jun" case 7: return "Jul" case 8: return "Aug" case 9: return "Sep" case 10: return "Oct" case 11: return "Nov" case 12: return "Dec" default: print("Error fetching months") return "Month" } } else { return nil } }
sumber
Kode SWIFT 2.0 untuk menampilkan minggu ini mulai hari Senin.
@IBAction func show (pengirim: AnyObject) {
// Getting Days of week corresponding to their dateFormat let calendar = NSCalendar.currentCalendar() let dayInt: Int! var weekDate: [String] = [] var i = 2 print("Dates corresponding to days are") while((dayInt - dayInt) + i < 9) { let weekFirstDate = calendar.dateByAddingUnit(.Day, value: (-dayInt+i), toDate: NSDate(), options: []) let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "EEEE dd MMMM" let dayOfWeekString = dateFormatter.stringFromDate(weekFirstDate!) weekDate.append(dayOfWeekString) i++ } for i in weekDate { print(i) //Printing the day stored in array } } // function to get week day func getDayOfWeek(today:String)->Int { let formatter = NSDateFormatter() formatter.dateFormat = "MMM-dd-yyyy" let todayDate = formatter.dateFromString(today)! let myCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)! let myComponents = myCalendar.components(.Weekday, fromDate: todayDate) let weekDay = myComponents.weekday return weekDay } @IBAction func DateTitle(sender: AnyObject) { // Getting currentDate and weekDay corresponding to it let currentDate = NSDate() let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "MMM-dd-yyyy" let dayOfWeekStrings = dateFormatter.stringFromDate(currentDate) dayInt = getDayOfWeek(dayOfWeekStrings) }
sumber
Kode ini untuk mencari seluruh minggu ini. Itu tertulis di Swift 2.0:
var i = 2 var weekday: [String] = [] var weekdate: [String] = [] var weekmonth: [String] = [] @IBAction func buttonaction(sender: AnyObject) { let currentDate = NSDate() let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "MMM-dd-yyyy" let dayOfWeekStrings = dateFormatter.stringFromDate(currentDate) let weekdays = getDayOfWeek(dayOfWeekStrings) let calendar = NSCalendar.currentCalendar() while((weekdays - weekdays) + i < 9) { let weekFirstDate = calendar.dateByAddingUnit(.Day, value: (-weekdays+i), toDate: NSDate(), options: []) let dayFormatter = NSDateFormatter() dayFormatter.dateFormat = "EEEE" let dayOfWeekString = dayFormatter.stringFromDate(weekFirstDate!) weekday.append(dayOfWeekString) let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "dd" let dateOfWeekString = dateFormatter.stringFromDate(weekFirstDate!) weekdate.append(dateOfWeekString) let monthFormatter = NSDateFormatter() monthFormatter.dateFormat = "MMMM" let monthOfWeekString = monthFormatter.stringFromDate(weekFirstDate!) weekmonth.append(monthOfWeekString) i++ } for(var j = 0; j<7 ; j++) { let day = weekday[j] let date = weekdate[j] let month = weekmonth[j] var wholeweek = date + "-" + month + "(" + day + ")" print(wholeweek) } } func getDayOfWeek(today:String)->Int { let formatter = NSDateFormatter() formatter.dateFormat = "MMM-dd-yyyy" let todayDate = formatter.dateFromString(today)! let myCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)! let myComponents = myCalendar.components(.Weekday, fromDate: todayDate) let daynumber = myComponents.weekday return daynumber }
Outputnya akan seperti ini:
14 Maret (Senin) 15 Maret (Selasa) 16 Maret (Rabu) 17 Maret (Kamis) 18 Maret (Jumat) 19 Maret (Sabtu) 20 Maret (Minggu)
sumber
Swift 3: Fungsi pembantu Xcode 8:
func getDayOfWeek(fromDate date: Date) -> String? { let cal = Calendar(identifier: .gregorian) let dayOfWeek = cal.component(.weekday, from: date) switch dayOfWeek { case 1: return "Sunday" case 2: return "Monday" case 3: return "Tuesday" case 4: return "Wednesday" case 5: return "Thursday" case 6: return "Friday" case 7: return "Saturday" default: return nil } }
sumber
Agar Swift4 mendapatkan hari kerja dari string
func getDayOfWeek(today:String)->Int { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd" let todayDate = formatter.date(from: today)! let myCalendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)! let myComponents = myCalendar.components(NSCalendar.Unit.weekday, from: todayDate) let weekDay = myComponents.weekday return weekDay! } let weekday = getDayOfWeek(today: "2018-10-10") print(weekday) // 4
sumber