I am trying to make my date display such as "March 2nd, 2018 10:00pm". I tried "MM-dd-yyyy" and "yyyy-MM-dd hh:mm:ss" but it seems like none of these combinations are getting the date I desire.The function to pick the date is sendRequest and it is using a UIDatePicker.
func getCurrentDateTimeFromTimeStamp(timestamp:String)->String{
let date = NSDate(timeIntervalSince1970:Double(timestamp)!)
let formatter = DateFormatter()
formatter.dateFormat = "MMMM d, yyyy HH:mm a"
return formatter.string(from: date as Date)
}
let dateCellVar = request.timestamp
let dateString = dateCellVar.description
dateCell.textLabel?.text = self.getCurrentDateTimeFromTimeStamp(timestamp: dateString)
class Request {
var timestamp:Double
init(dict: [String: Any]) {
self.timestamp = dict["timestamp"] as? Double ?? 0.0
}
func sendRequest(){
print("HEY:")
guard let user = currentUser else { return }
print("USER: \(user.firstLastName)")
if let da = dateField.text{
print(da)
}
print(timeField.text)
print(locationField.text)
print(messageTextView.text)
guard let pickedDate = pickedDate else { return print("pickedDate") }
guard let date = dateField.text else { return print("pickedDate") }
guard let time = timeField.text else { return print("time") }
guard let location = locationField.text else { return print("location")}
let db = Database.database().reference()
let ref = db.child("requests").childByAutoId()
let data = [
"sender": user.uid,
"recipient": recipientUser.uid,
"name": user.firstLastName,
"photoURL": user.photoURL,
"location": location,
"date": date,
"time": time,
"pickedTimestamp": pickedDate.timeIntervalSince1970,
"message": messageTextView.text ?? "",
"status": "PENDING",
"timestamp": [".sv": "timestamp"]
] as [String:Any]
print("HEYO")
ref.setValue(data) { error, ref in
if error == nil {
print("Success")
} else {
print("Failed")
}
}
}
Based on your result, your timestamp is in milliseconds, not seconds. You need to divide by 1000.
You also have the wrong dateFormat. You want to use hh, not HH for the hour. H is for 24-hour time which makes no sense when using a for AM/PM. You should also avoid using dateFormat. Use dateStyle and timeStyle. Let the formatter give you a date formatted best for the user's locale.
Your code also does a lot of needless conversion. You get your timestamp as a Double and store it as a Double. But then your function to convert the timestamp you expect your number of seconds as a String which you then convert back to a Double. Avoid the needless use of a String.
To get the ordinal day, you can use Calendar to extract the day from your Date.
let date = Date()
let calendar = Calendar.current
let dateComponents = calendar.component(.day, from: date)
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .ordinal
let day = numberFormatter.string(from: dateComponents as NSNumber)
From there, you'd just code your date format with a DateFormatter and drop in the ordinal date you extracted above, like so:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM '\(String(describing: day!)),' yyyy h:mm a"
let dateString = "\(dateFormatter.string(from: date))"
print(dateString)
Additionally, the issue with your year probably stems from the number you're feeding it. timeIntervalSince1970 is expecting whole seconds, so make sure you're feeding it whole seconds.
init(timeIntervalSince1970: TimeInterval) Returns a date object
initialized relative to 00:00:00 UTC on 1 January 1970 by a given
number of seconds.
Adapted from this answer. Additionally, you may find this site helpful for formatting dates.
Related
How can I get local date and time in Swift?
let last_login = String(NSDate.date())
update: Xcode 8.2.1 • Swift 3.0.2
You can also use the Date method description(with locale: Locale?) to get user's localized time description:
A string representation of the Date, using the given locale, or if the locale
argument is nil, in the international format YYYY-MM-DD HH:MM:SS
±HHMM, where ±HHMM represents the time zone offset in hours and
minutes from UTC (for example, “2001-03-24 10:45:32 +0600”).
description(with locale: Locale?)
Date().description(with: .current) // "Monday, February 9, 2015 at 05:47:51 Brasilia Summer Time"
The method above it is not meant to use when displaying date and time to the user. It is for debugging purposes only.
When displaying local date and time (current timezone) to the user you should respect the users locale and device settings. The only thing you can control is the date and time style (short, medium, long or full). Fore more info on that you can check this post shortDateTime.
If your intent is to create a time stamp UTC for encoding purposes (iso8601) you can check this post iso8601
In case you want to get a Date object and not a string representation you can use the following snippet:
extension Date {
func localDate() -> Date {
let nowUTC = Date()
let timeZoneOffset = Double(TimeZone.current.secondsFromGMT(for: nowUTC))
guard let localDate = Calendar.current.date(byAdding: .second, value: Int(timeZoneOffset), to: nowUTC) else {return Date()}
return localDate
}
}
Use it like this:
let now = Date().localDate()
Leo's answer great. I just wanted to add a way to use it as a computed property.
var currentTime: String {
Date().description(with: .current)
}
Use it like so:
print(currentTime)
Or you can encapsulate it:
extension String {
static var currentTime: String {
Date().description(with: .current)
}
}
And then you can use it anywhere you use a string:
var time: String = .currentTime
use NSDateFormatter, either by setting the format
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "hh:mm"
println(dateFormatter.stringFromDate(NSDate()))
or styles
dateFormatter.dateStyle = .NoStyle
dateFormatter.timeStyle = .MediumStyle
I already found the answer.
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy HH:mm"
let dateInFormat = dateFormatter.stringFromDate(NSDate())
let expiryDate: Date = ...
let localizedDateString = DateFormatter.localizedString(from: expiryDate, dateStyle: .medium, timeStyle: .short)
"10 Sep 2017, 14:37"
To get back the most common string formats (when dealing with queries and databases):
Swift 4, 5
2019-01-09T01:07:04Z (RFC3339 in GMT/Zulu time)
let f = ISO8601DateFormatter()
f.formatOptions = [.withInternetDateTime]
let s = f.string(from: Date())
2019-01-08T17:04:16-08:00 (RFC3339 accounting for local time zone)
let f = ISO8601DateFormatter()
f.formatOptions = [.withInternetDateTime]
f.timeZone = TimeZone.current
let s = f.string(from: Date())
2019-01-09 (standard date stamp in GMT/Zulu time)
let f = ISO8601DateFormatter()
f.formatOptions = [.withFullDate, .withDashSeparatorInDate]
let s = f.string(from: Date())
2019-01-08 (standard date stamp accounting for local time zone)
let f = ISO8601DateFormatter()
f.formatOptions = [.withFullDate, .withDashSeparatorInDate]
f.timeZone = TimeZone.current
let s = f.string(from: Date())
All four strings represent the exact same point in time. And remember that sorting these strings in alphabetical order also sorts them into chronological order, which makes this data database agnostic (which I always aim for).
You have to use NSDateFormatter
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MMMM dd, yyyy HH:mm"
dateFormatter.locale = "en" // Change "en" to change the default locale if you want
let stringDate = dateFormatter.stringFromDate(date)
Refactor the answer with swift 5 base on #lajosdeme. My location is in China.
import Foundation
let date = Date() // It is not the local time, less than 8 hours
print(date) // 2022-08-05 08:04:20 +0000
extension Date {
static func localDate() -> Date {
let nowUTC = Date()
let timeZoneOffset = Double(TimeZone.current.secondsFromGMT(for: nowUTC))
guard let localDate = Calendar.current.date(byAdding: .second, value: Int(timeZoneOffset), to: nowUTC) else {
return nowUTC
}
return localDate
}
}
// It is the local time
print(Date.localDate()) // 2022-08-05 16:04:20 +0000
Swift 4
To get current date and time
let currentDate = Date()
print(currentDate) //this will return current date and time
but that will be in date type to convert date into string
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy HH:mm" //give the formate according to your need
let dateStr = dateFormatter.string(from: currentDate) //which will give the string of current date and time in required dateformate
My understanding of Swift Date is that Date is a time point without any calendar or timezone information. I think it is GMT time. If you want to show a date in a specified timezone, you have to use DateFormat API to format the date to a string.
I have an iOS app TapToCount-3W to make notes with date and GPS location information. When I travel, I use it to record/tap a note with date and GPS. The dates are local date when I am in travel countries. However, the problem I found is that when I come back home, the travel dates displayed are in my home country dates instead of those travel country timezones.
I am working on updates with my app now. The solution is to add timezone information when a tap is made. With date and timezone information, the localized dates will be correctly displayed.
The method as recommended in this QA to extend Date is actually to create date from Date() from second offset from GMT time. It is a GMT time and different date from Date().
The following codes are from my updates(I also included #lajosdeme method as comparison):
extension Date {
private func getLocalByID(_ identifier: String?) -> Locale
{
let local: Locale
if let id = identifier, !id.isEmpty {
local = Locale(identifier: id)
} else {
local = Locale.current
}
return local
}
func localizedString(
timezone: String?,
dateStyle: DateFormatter.Style = .short,
timeStyle: DateFormatter.Style = .long
) -> String
{
let dtFormater = DateFormatter()
let tz: String = timezone ?? ""
dtFormater.locale = getLocalByID(tz)
dtFormater.dateStyle = dateStyle
dtFormater.timeStyle = timeStyle
if let timeZone = TimeZone(identifier: tz) {
dtFormater.timeZone = timeZone
}
return dtFormater.string(from: self)
}
func dateForTimezone(_ timezone: String?) -> Date {
let nowUTC = Date()
let tz: TimeZone
if let timezone = timezone,
let v = TimeZone(identifier: timezone)
{
tz = v
} else {
tz = TimeZone.current
}
let timeZoneOffset =
Double(tz.secondsFromGMT(for: nowUTC))
if let dt =
Calendar.current.date(byAdding: .second, value: Int(timeZoneOffset), to: nowUTC)
{
return dt
}
else {
return Date()
}
}
}
// Test above extension in Playground
// [SwiftFiddle][3]
let dt1 = Date()
let tz = "America/Edmonton"
let dt2 = dt1.description(with: .current)
let dt3 = dt1.localizedString(timezone: tz)
let dt4 = dt1.dateForTimezone(tz)
print("Timezone: \(tz)\nDate: \(dt1)\ndescription: \(dt2)\nlocalized string: \(dt3)\ndateForTimezone: \(dt4)")
Here are the test result from SwiftFiddle playground:
Timezone: America/Edmonton
Date: 2022-06-03 15:41:23 +0000
description: Friday, June 3, 2022 at 3:41:23 PM Coordinated Universal Time
localized string: 6/3/22, 9:41:23 AM GMT-6
dateForTimezone: 2022-06-03 09:41:23 +0000
This is the database below. I need to take the 'caption' child which is a timestamp and convert it into date format in Xcode.
"UserS" : {
"K1eqsVZfKGgIf0sS1UZcPNxY62x1" : {
"Education" : "William Taft Elementary",
"PhotoPosts" : "https://firebasestorage.googleapis.com/v0/b/daylike-2f938.appspot.com/o/images%2FPhotoPosts?alt=media&token=fd92856e-f7d2-4558-82c4-ee49f580icc5e",
"caption" : 1563277511065,
"users" : "jane19#aol.com"
},
This is what I have under super view did load.
let databaseRef = Database.database().reference()
let uid = Auth.auth().currentUser!.uid
databaseRef.child("UserS").child(uid).child("caption").observeSingleEvent(of: .value, with: { (snapshot) in
guard let message = snapshot.value as? [String:String] else { return }
let caption = message["caption"]
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss.SSSSxxx"
guard let date = dateFormatter.date(from: caption!) else {
fatalError("ERROR: Date conversion failed due to mismatched format.")
}
if (snapshot.exists()){
print ("mmmmmmm")
}else{
print("badddddd")
}
})
At the end I want to print out the timestamp in date format so that I can check it it is 24 hours old.
"13 digit timestamp" is just and number of milliseconds since 1st of January 1970 UTC.
Date already has initializer for timestamps since that timepoint. Only difference is it's number of seconds, not milliseconds.
Therefore only thing you should do is to divide it by 1000:
// skipping unrelevant boilerplate
// assuming caption is Int
let date = Date(timeIntervalSince1970: TimeInterval(caption)/1000.0) // for `1563277511065` it would be `"Jul 16, 2019 at 11:45 AM"`(UTC)
// skipping unrelevant boilerplate
EDIT:
To check if date from timestamp is not "older" than 24 hours you have several options:
Get difference between the date and now and check if it's under 24 hours:
let secondsInDay = 86400
if (-date.timeIntervalSinceNow < secondsInDay) { … } // negative, because that date would be in the past
Get one day before using calendar:
let calendar = Calendar.autoupdatingCurrent // or whatever you prefer
let dayBefore = calendar.date(
byAdding: .day,
value: -1,
to: Date(),
wrappingComponents: true)!
if (date > dayBefore) { … }
Since you listen to UserS->caption then snapshot.value is an Int . so you need
databaseRef.child("UserS").child(uid).child("caption").observeSingleEvent(of: .value, with: { (snapshot) in
guard let caption = snapshot.value as? Int else { return }
print(caption)
let date = Date(timeIntervalSince1970: TimeInterval(caption)/1000.0)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss.SSSSxxx"
let res = dateFormatter.string(from: date)
print(res)
}
Edit:
if Calendar.current.dateComponents([.day], from:date, to: Date()).day! > 0 {
/// at least 1 day passed
}
I'm trying to make an attendance app and I am really confused about date and time in iOS and Firebase.
I use date as Key, this is the structure of my Firebase database.
--Employees
--Unique_ID
--Details
Name: John
--Attendance
--dateToday
Timein: 8:00 AM
Timeout: 5:00 PM
BreakStart: 12:00 PM
BreakFinish: 1:00 PM
This is my code to get the date timestamp I used as Key
override func viewDidLoad() {
super.viewDidLoad()
let now = NSDate()
let nowTimeStamp = self.getCurrentTimeStampWOMiliseconds(dateToConvert: now)
// I save this dateToday as Key in Firebase
dateToday = nowTimeStamp
}
func getCurrentTimeStampWOMiliseconds(dateToConvert: NSDate) -> String {
let objDateformat: DateFormatter = DateFormatter()
objDateformat.dateFormat = "yyyy-MM-dd"
let strTime: String = objDateformat.string(from: dateToConvert as Date)
let objUTCDate: NSDate = objDateformat.date(from: strTime)! as NSDate
let milliseconds: Int64 = Int64(objUTCDate.timeIntervalSince1970)
let strTimeStamp: String = "\(milliseconds)"
return strTimeStamp
}
But when I convert it back to date I get 2017-09-22 16:00:00 +0000, which is wrong because it is 23rd of September in my location.
What is the right code to use so that I can get the correct date timestamp and time timestamp?
For saving Current time to firebase database I use Unic Epoch Conversation:
let timestamp = NSDate().timeIntervalSince1970
and For Decoding Unix Epoch time to Date().
let myTimeInterval = TimeInterval(timestamp)
let time = NSDate(timeIntervalSince1970: TimeInterval(myTimeInterval))
If you just want the unix timestamp, create an extension:
extension Date {
func currentTimeMillis() -> Int64 {
return Int64(self.timeIntervalSince1970 * 1000)
}
}
Then you can use it just like in other programming languages:
let timestamp = Date().currentTimeMillis()
First I would recommend you to store your timestamp as a NSNumber in your Firebase Database, instead of storing it as a String.
Another thing worth mentioning here, is that if you want to manipulate dates with Swift, you'd better use Date instead of NSDate, except if you're interacting with some Obj-C code in your app.
You can of course use both, but the Documentation states:
Date bridges to the NSDate class. You can use these interchangeably in
code that interacts with Objective-C APIs.
Now to answer your question, I think the problem here is because of the timezone.
For example if you print(Date()), as for now, you would get:
2017-09-23 06:59:34 +0000
This is the Greenwich Mean Time (GMT).
So depending on where you are located (or where your users are located) you need to adjust the timezone before (or after, when you try to access the data for example) storing your Date:
let now = Date()
let formatter = DateFormatter()
formatter.timeZone = TimeZone.current
formatter.dateFormat = "yyyy-MM-dd HH:mm"
let dateString = formatter.string(from: now)
Then you have your properly formatted String, reflecting the current time at your location, and you're free to do whatever you want with it :) (convert it to a Date / NSNumber, or store it directly as a String in the database..)
in Swift 5
extension Date {
static var currentTimeStamp: Int64{
return Int64(Date().timeIntervalSince1970 * 1000)
}
}
call like this:
let timeStamp = Date.currentTimeStamp
print(timeStamp)
Thanks #lenooh
The simple way to create Current TimeStamp. like below,
func generateCurrentTimeStamp () -> String {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy_MM_dd_hh_mm_ss"
return (formatter.string(from: Date()) as NSString) as String
}
you can call like this:
let timeStmp = generateCurrentTimeStamp()
print("time stamp: \(timeStmp)")
If you code for iOS 13.0 or later and want a timestamp, then you can use:
let currentDate = NSDate.now
On expanding #MacacoAzul's answer here is my current working example :
import SwiftUI
struct TimestampDemo: View {
var body: some View {
Text(getActualTimeStamp(1))
.padding(10)
Text(getActualTimeStamp(2))
.padding(10)
Text(getActualTimeStamp(3))
.padding(10)
Text(getActualTimeStamp(4))
.padding(10)
}
func getActualTimeStamp(_ tipo:Int) -> String {
let date = Date()
let formatter = DateFormatter()
if tipo == 1{
formatter.dateFormat = "dd/MM/yyyy"
} else if tipo == 2{
formatter.dateFormat = "yyyy-MM-dd HH:mm"
}else if tipo == 3{
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
}
else if tipo == 4 {
formatter.dateFormat = "dd-MM-yyyy"
}
return formatter.string(from: date)
}
}
struct TimestampDemo_Previews: PreviewProvider {
static var previews: some View {
TimestampDemo()
}
}
Swift Language Version : 5
When we convert a UTC timestamp (2017-11-06 20:15:33 -08:00) into a Date object, the time zone is zeroed out to GMT. For calculating time intervals, this isn't an issue, but it can be for rendering times in the UI.
I favor the RFC3339 format (2017-11-06T20:15:33-08:00) for its universality. The date format in Swift is yyyy-MM-dd'T'HH:mm:ssXXXXX but RFC3339 allows us to take advantage of the ISO8601DateFormatter:
func getDateFromUTC(RFC3339: String) -> Date? {
let formatter = ISO8601DateFormatter()
return formatter.date(from: RFC3339)
}
RFC3339 also makes time-zone extraction simple:
func getTimeZoneFromUTC(RFC3339: String) -> TimeZone? {
switch RFC3339.suffix(6) {
case "+05:30":
return TimeZone(identifier: "Asia/Kolkata")
case "+05:45":
return TimeZone(identifier: "Asia/Kathmandu")
default:
return nil
}
}
There are 37 or so other time zones we'd have to account for and it's up to you to determine which ones, because there is no definitive list. Some standards count fewer time zones, some more. Most time zones break on the hour, some on the half hour, some on 0:45, some on 0:15.
We can combine the two methods above into something like this:
func getFormattedDateFromUTC(RFC3339: String) -> String? {
guard let date = getDateFromUTC(RFC3339: RFC3339),
let timeZone = getTimeZoneFromUTC(RFC3339: RFC3339) else {
return nil
}
let formatter = DateFormatter()
formatter.dateFormat = "h:mma EEE, MMM d yyyy"
formatter.amSymbol = "AM"
formatter.pmSymbol = "PM"
formatter.timeZone = timeZone // preserve local time zone
return formatter.string(from: date)
}
And so the string "2018-11-06T17:00:00+05:45", which represents 5:00PM somewhere in Kathmandu, will print 5:00PM Tue, Nov 6 2018, displaying the local time, regardless of where the machine is.
As an aside, I recommend storing dates as strings remotely (including Firestore which has a native date object) because, I think, remote data should agnostic to create as little friction between servers and clients as possible.
you can even create a function to return different time stamps depending on your necessity:
func dataatual(_ tipo:Int) -> String {
let date = Date()
let formatter = DateFormatter()
if tipo == 1{
formatter.dateFormat = "dd/MM/yyyy"
} else if tipo == 2{
formatter.dateFormat = "yyyy-MM-dd HH:mm"
} else {
formatter.dateFormat = "dd-MM-yyyy"
}
return formatter.string(from: date)
}
I am parsing json using Swifty json. Now i have a key as "create_date" which can have a timestamp & as well as a date string like "2017-08-17 20:00:00".Now i am not sure when it will be a string date or it is a timestamp.I am using below code to parse this
if let timeInterval = dic?["created_at"].doubleValue {
print("timeinterval is \(timeInterval)")
date1 = NSDate(timeIntervalSince1970: (timeInterval / 1000))
date = self.getStrDateFromDate(dob: date1!) as String
}
if use dict["create_date"].doubleValue so if it a string date then it r return me 2017 & in case of timestamp it return some timestamp as 15383673563465 .
Now how do i identify if is a date or a timestamp ?
Use optional binding and cast down the value to Double with the double property of SwiftyJSON. If the downcast succeeds create the string from the Date otherwise use the date string directly.
let dateString : String
if let timeInterval = dic?["created_at"].double {
print("timeinterval is \(timeInterval)")
date1 = Date(timeIntervalSince1970: timeInterval / 1000)
dateString = self.getStrDateFromDate(dob: date1!) as String
} else {
dateString = dic?["created_at"].stringValue
}
Side note:
Why do you (bridge) cast a result to string (from getStrDateFromDate) which is supposed to be a string?
I would try a DateFormatter with the format of your possible date string, then try to convert it to a double. Or vise-versa. The order really doesn't matter too much, although it may be slightly less expensive to check for the double first.
import Foundation
func convertDate(dateString:String) -> Date? {
// try `Double`
if let timestamp = Double(dateString) {
return Date(timeIntervalSince1970: timestamp)
}
// try `DateFormatter`
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
if let date = formatter.date(from: dateString) {
return date
}
// give up
return nil
}
let dateString1 = String(Date().timeIntervalSince1970)
let dateString2 = "2017-08-17 20:00:00"
let dateString3 = "something"
print(convertDate(dateString: dateString1) ?? "unknown")
print(convertDate(dateString: dateString2) ?? "unknown")
print(convertDate(dateString: dateString3) ?? "unknown")
// 2017-08-17 15:15:27 +0000
// 2017-08-18 00:00:00 +0000
// unknown
Note that the default description for a Date uses GMT. In my case it's off by 4 hours, which is why the displayed time is 4 hours different from I entered.
I have to display date in different format.
For eg.
21st July
I didn't find anything to convert my date in this format. If anyone knows please help me.
Swift
extension Date {
func dateFormatWithSuffix() -> String {
return "dd'\(self.daySuffix())' MMMM yyyy"
}
func daySuffix() -> String {
let calendar = Calendar.current
let components = (calendar as NSCalendar).components(.day, from: self)
let dayOfMonth = components.day
switch dayOfMonth {
case 1, 21, 31:
return "st"
case 2, 22:
return "nd"
case 3, 23:
return "rd"
default:
return "th"
}
}
}
Example
let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = date.dateFormatWithSuffix()
print(dateFormatter.string(from: date))
// Output for current date: 22nd May 2019
func setCurrentDate() {
let date = Date()
// Use this to add st, nd, th, to the day
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .ordinal
numberFormatter.locale = Locale.current
//Set other sections as preferred
let monthFormatter = DateFormatter()
monthFormatter.dateFormat = "MMM"
// Works well for adding suffix
let dayFormatter = DateFormatter()
dayFormatter.dateFormat = "dd"
let dayString = dayFormatter.string(from: date)
let monthString = monthFormatter.string(from: date)
// Add the suffix to the day
let dayNumber = NSNumber(value: Int(dayString)!)
let day = numberFormatter.string(from: dayNumber)!
yourDateLabel.text = "\(day) \(monthString)"
}
Label will currently be set to 25th May
You can use NSDateFormatter to display your NSDate. It has properties such as dateStyle, and timeStyle which can easily be altered to get your desired format. If you need more flexibility there's the dateFormat property as well.
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
formatter.stringFromDate(NSDate())