Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Datepicker picks wrong date

I am converting date to day, but if I just println() the current selected date in the datepicker, I get wrong time and wrong date.

@IBOutlet weak var datepicker: UIDatePicker!

@IBAction func displayDay(sender: AnyObject) {
    var chosenDate = self.datepicker.date

    println(chosenDate)

I've following date selected date. enter image description here

And click on the button underneath datepicker. I get following line in output

 2015-01-11 20:17:37 +0000

Can somebody tell me.what's wrong with output?

like image 298
MFarooqi Avatar asked Jan 11 '15 20:01

MFarooqi


3 Answers

This is fine because the date picker uses its local time but it stores UTC time. It means your local time offset is -5h. You can do as follow to extract the right date and time from it:

extension NSDate {
    var localizedDescription: String {
       return descriptionWithLocale(NSLocale.currentLocale()) ?? ""
    }
}

println(chosenDate.localizedDescription)

Swift 3 or later

extension Date {
    var localizedDescription: String {
        return description(with: .current)
    }
}

Date().localizedDescription  // "Monday, October 16, 2017 at 2:24:11 AM Brasilia Summer Time"
like image 133
Leo Dabus Avatar answered Sep 24 '22 21:09

Leo Dabus


Swift 3.0 - If You want to get a result in date format then use the following code.

extension Date {

    var convertedDate:Date {

        let dateFormatter = DateFormatter();

        let dateFormat = "dd MMM yyyy";
        dateFormatter.dateFormat = dateFormat;
        let formattedDate = dateFormatter.string(from: self);

        dateFormatter.locale = NSLocale.current;
        dateFormatter.timeZone = TimeZone(abbreviation: "GMT+0:00");

        dateFormatter.dateFormat = dateFormat as String;
        let sourceDate = dateFormatter.date(from: formattedDate as String);

        return sourceDate!;
    }
}

print(pickerView.date.convertedDate)
like image 32
AtulParmar Avatar answered Sep 20 '22 21:09

AtulParmar


Use this method to get correct date:

func getDateStamp(date:String)-> String{

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss +SSSS"
    dateFormatter.timeZone = TimeZone(abbreviation: "UTC")

    guard let date = dateFormatter.date(from: date) else {
        //  assert(false, "no date from string")
        return ""
    }

    dateFormatter.dateFormat = "dd MMMM,yyyy" //"yyyy-MM-dd"
    dateFormatter.timeZone = TimeZone.current

    let st = dateFormatter.string(from: date)

    return st
}
like image 35
Sandeep Yadav Avatar answered Sep 20 '22 21:09

Sandeep Yadav