Search code examples
swiftswift3nsdateios10

NSDate which is returned is incorrect


I am build a function to get the date for the Chinese new year from the date which is passed from a datePicker. the convertDateFormater converts a string formatted date to a date object. the date which i get back is

Returned date = "03-Feb-2030" for the year "1970-05-22"

but if i run the current date with "NSDate() as Date" i get the right output. for the year 2016.

func convertDateFormater(date: String) -> Date
{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"//this your string date format
dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone!
let date = dateFormatter.date(from: date)
return date!
}

var inputDate1 = convertDateFormater(date: "1970-05-22")
print(inputDate1)

let chineseCalendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.chinese)!
let formatter: DateFormatter = {
let fmt = DateFormatter()
fmt.dateStyle = .full
fmt.timeStyle = .full
fmt.dateFormat = "dd-MMM-yyyy"
return fmt
}()

var comps = chineseCalendar.components([.year], from: inputDate)
guard let newYear = chineseCalendar.date(from: comps) else {   fatalError("no date for \(comps.year)")}
let getNewYear = formatter.string(from: newYear)
print("\(NSDate() as Date) : \(getNewYear) - \(newYear)")

Solution

  • In the Gregorian calendar, there are two eras: the current "Common Era" (abbreviated "CE" and also known as "Anno Domini" or "AD") and "Before Common Era" (abbreviated "BCE" and also known as "Before Christ" or "BC"). So a year number on the Gregorian calendar is ambiguous: "1970" by itself can mean either "1970 CE" or "1970 BCE". We usually assume CE when no era is specified.

    I know almost nothing about the Chinese calendar, but I know it has many more eras than the Gregorian calendar, so a year number on the Chinese calendar is even more ambiguous. The code you posted doesn't do anything about eras. So I copied and pasted your code into a playground and made one change:

    var comps = chineseCalendar.components([.era, .year], from: inputDate)
    //                                      ^^^^^^
    

    The output:

    1970-05-22 00:00:00 +0000
    2016-11-30 01:40:12 +0000 : 06-Feb-1970 - 1970-02-06 06:00:00 +0000
    

    Indeed, 1970-02-06 was the date of the Chinese new year in 1970 CE on the Gregorian calendar.