0

I need to convert date saved in a NSDate with format yyyy-MM-dd to NSString with format like /Date(1430604000000+0200)/ in swift, because I have to save it in my DB SQLite.

In this way i convert /date()/ to nsdate yyyy-MM-dd:

var charactersToRemove: NSCharacterSet = NSCharacterSet.decimalDigitCharacterSet().invertedSet
                var milliseconds:NSString = dateString.stringByTrimmingCharactersInSet(charactersToRemove)
                var dateTemp:NSDate!
                if (milliseconds != "" && !milliseconds.isEqualToString("62135596800000") )
                {
                    var seconds:NSTimeInterval = milliseconds.doubleValue / 1000
                    dateTemp = NSDate(timeIntervalSince1970: seconds)
                }

But now I need to reverse it. I need to convert nsdate yyyy-MM-dd to string /date()/.

Thank you.

Chongzl
  • 589
  • 1
  • 9
  • 25
  • Is 1430604000000+0200 just the UTC timestamp? If so, think about it. Using `NSDate().timeIntervalSince1970` you can get the timestamp from your date and from there it shouldn't be too difficult to replace the decimal in the double that is NSTimeInterval with a + – Ian Dec 30 '14 at 08:28
  • also check this out http://stackoverflow.com/a/1000959/3810673 – Ian Dec 30 '14 at 08:34

1 Answers1

0

I didn't add sign check but I ended up something like this.

let format = "yyyy-MM-dd"
let formatter = NSDateFormatter()
formatter.timeZone = NSTimeZone.localTimeZone()
formatter.dateFormat = format

var dateString = "2014-12-30" // your input date
let date = formatter.dateFromString(dateString) 
let timestamp: NSTimeInterval = date!.timeIntervalSince1970 * 1000.0

let result = String(format: "/Date(%.0f+%02d00)/", timestamp,formatter.timeZone.secondsFromGMT/3600)
cyt
  • 1,164
  • 14
  • 15