0

I am new to programming and recently started learning Swift language. To test my learning i am trying to make an app like "Alarm Clock". Initially i thought that i can assign datepicker.date to notification date but soon i realize that datepicker is not giving the exact value. I had no idea how to do it but after a good amount of research on this website i got some understanding about how to implement. I started making the app but now i stuck with a problem. I created a date picker to set the alarm and i used NSDateFormeter function to extract the string from the date. and i made an array with that string and used dateFromComponents to make a date. When i try to print them, the array giving correct numbers but after making date with it the date is coming out different. Please help me to solve this. Thank you very much for help.

import UIKit
import Foundation

class ViewController: UIViewController {

  var myArray = [String]()
  @IBOutlet weak var mydatePicker: UIDatePicker!
 override func viewDidLoad() {
    super.viewDidLoad()

 }

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


@IBAction func mydatepickerAction(sender: AnyObject) {

   var daFormet = NSDateFormatter()

    //For ex: 2015:01:17:20:05
   daFormet.dateFormat = "YYY:MM:dd:HH:mm"

   //This makes datestring from Datepickersdate
   var dateString:String = daFormet.stringFromDate(mydatePicker.date)

    //Makes an array from the date String
    myArray = dateString.componentsSeparatedByString(":")

}


@IBAction func myButton(sender: AnyObject) {


    println(myArray)

    //Creates a date from  components
    var newMyDate:NSDate = dateFromComponents(myArray[2] .toInt()!, month: myArray[1] .toInt()!, year: myArray[0] .toInt()!, hour: myArray[3] .toInt()!, minute: myArray[0] .toInt()!, second: 00)

    println(newMyDate)
    var date = NSDate()
    println(date)

}

func dateFromComponents(day:Int, month:Int, year:Int, hour:Int, minute:Int, second:Int) -> NSDate {
    var cal = NSCalendar(calendarIdentifier: NSGregorianCalendar)!
    cal.timeZone = NSTimeZone.localTimeZone()
    var comps = NSDateComponents()
    comps.day = day
    comps.year = year
    comps.second = second
    comps.hour = hour
    comps.minute = minute
    comps.month = month
    return cal.dateFromComponents(comps)!
 }

}
ilvcs
  • 103
  • 1
  • 17
  • http://stackoverflow.com/questions/27348209/user-set-time-for-notification-in-swift/27349421#27349421 – Leo Dabus Jan 18 '15 at 03:45
  • This might work but, i want to know why i am not able to make a correct date from the components. – ilvcs Jan 18 '15 at 15:23

1 Answers1

0

You are using the wrong format for year. You have to use "y" (lowercase) instead of "YYY".

Leo Dabus
  • 229,809
  • 59
  • 489
  • 571