2017-05-06 2 views
6

나는 현재 달로할지 모르지만 나는 할 수 없다. 나는 어떻게 이것을 달성 할 수 있는가.나는 현재 달을 신속한 문자열로 얻을 수있는 방법 :

let date = NSDate() 
    let calendar = NSCalendar.currentCalendar() 
    let components = calendar.components([.Day , .Month , .Year], fromDate: date) 

    let year = components.year 
    let month = components.month 
    let day = components.day 

나는 이것을했지만 효과가 없습니다.

+0

당신이 문자열로 서수를 원하십니까 아래처럼 그것으로 코드

extension Date { func getMonthName() -> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "MMMM" let strMonth = dateFormatter.string(from: self) return strMonth } } 

가져 오기 작업 아래

시도, 월 이름 또는 뭔가 다른 (어떤 언어)? 그리고 스위프트 3으로 업데이트하는 것을 고려하십시오. 그것은 미래입니다. – vadian

+0

@vadian 3은 이미 과거입니다. 우리는 3.1에 있습니다 –

+0

@LeoDabus 물론 메이저 업그레이드처럼'≥'의 관점에서 스위프트 3을 의미합니다. – vadian

답변

16
let now = NSDate() 
let dateFormatter = NSDateFormatter() 
dateFormatter.dateFormat = "LLLL" 
let nameOfMonth = dateFormatter.stringFromDate(now) 
+0

감사합니다 ...... – iron

+2

독립형 달의 올바른 형식은 LLLL입니다. http://userguide.icu-project.org/formatparse/datetime –

0

DateFormatter()를 사용하면 Date에 대한 확장에이 항목이 사용됩니다.

프로젝트의 어디서나이를 전역 범위에 추가하십시오.

extension Date { 
    func monthAsString() -> String { 
      let df = DateFormatter() 
      df.setLocalizedDateFormatFromTemplate("MMM") 
      return df.string(from: self) 
    } 

}

그런 다음 당신은 당신의 코드에서이 어디서나 사용할 수 있습니다.

let date = Date() 
date.monthAsString() // Returns current month e.g. "May" 
+0

NSdate 날짜를 사용해야합니까 선언되지 않은 .... swift 2 – iron

5

당신이 스위프트 다음 3.0 확장과 날짜 클래스를 사용하는 경우 갈 좋은 방법입니다.

let date = Date() 

let monthString = date.getMonthName() 
+0

나는 스위프트 2를 사용하고 있습니다. – iron

+0

만약 당신이 형편이 좋다면 스위프트 3.0을 타보세요. bcz 그것의 많은 최신 일어나 ** 신속한 ** –

관련 문제