Date picking time from another time zone

Asked

Viewed 543 times

0

I have a big problem, I need to store the date and time selected by the user in order to generate the notifications at the right time. The date and time is captured by a Picker date and when caught as String comes in the correct manner "Sep 27, 2016 13:04", but when I’m going to make the conversion to Nsdate the time gets messed up, 2016-09-27 16:04. Could anyone help solve this problem? I’m testing with the iPhone and not in the simulator

let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "dd MMM yyyy HH:mm"
    dateFormatter.locale = NSLocale.currentLocale()
    dateFormatter.timeZone = NSTimeZone.localTimeZone()
    let date2:NSDate!
        date2 = dateFormatter.dateFromString(dateStr4)
    dateFormatter.dateFormat = "dd/MM/yyyy HH:mm"

    if let unwrappedDate = date2 {

        print(dateFormatter.stringFromDate(unwrappedDate))// aqui aparece a data e hora de maneira correta 27/09/2016 13:09
        print("--->",unwrappedDate) // aqui a hora já fica zoada 27/09/2016 16:09
        criaNotificacoes(unwrappedDate, comIntervalo: util.valorIntervalo(campoIntervalo.text!), totalDias: util.valorTempoDias(campoPeriodo.text!))
    }else{
        print("tratar erro ")
    }
  • When Voce print the date, will always appear the time without the time zone (UTC/GMT time), do not worry about it, the date does not guard your time zone, The only time you need it is to show the user and the time it will appear will depend on the location of the user at the time you display the date using Dateformatter.

  • 1

    When you receive a String with date from your API and have at the end +0000 or Z stands for UTC/GMT time

1 answer

0

You are printing, but you are not saving the correct date at any constant. Try saving dateFormatter.stringFromDate(unwrappedDate) in a constant and call her in the code instead of unwrappedDate.

Sort of like this:

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd MMM yyyy HH:mm"
dateFormatter.locale = NSLocale.currentLocale()
dateFormatter.timeZone = NSTimeZone.localTimeZone()
let date2:NSDate!
    date2 = dateFormatter.dateFromString(dateStr4)
dateFormatter.dateFormat = "dd/MM/yyyy HH:mm"

if let unwrappedDate = date2 {
    let data = dateFormatter.stringFromDate(unwrappedDate)
    print(data)
    print("--->", data)
    criaNotificacoes(data, comIntervalo: util.valorIntervalo(campoIntervalo.text!), totalDias: util.valorTempoDias(campoPeriodo.text!))
}else{
    print("tratar erro ")
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.