Swift - NSDate - remove part of date
You ask:
How can I remove extra +0000 digits?
I'm not sure what you mean, because the resulting dateStr
does have the +0000
removed.
But let's step back and consider the right way to parse a date string in the format of 2015-02-22T20:58:16+0000
. You should use a locale
of en_US_POSIX
as described in Apple Technical Q&A 1480:
let myDate = "2015-02-22T20:58:16+0000"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
let date = dateFormatter.dateFromString(myDate)
When you then want to format that for the end user, reset the locale
back to currentLocale
:
dateFormatter.locale = NSLocale.currentLocale()
dateFormatter.dateFormat = "eee MMM dd yyyy"
let dateStr = dateFormatter.stringFromDate(date!)
The dateStr
then becomes:
Sun Feb 22 2015
Or, perhaps better, for better localization behavior, use dateFormatFromTemplate
:
let locale = NSLocale.currentLocale()
dateFormatter.locale = locale
dateFormatter.dateFormat = NSDateFormatter.dateFormatFromTemplate("eeeMMMdyyyy", options: 0, locale: locale)
let dateStr = dateFormatter.stringFromDate(date!)
In the US, it will appear like above, but in England it will appear as:
Sun, 22 Feb 2015
Or use one of the standard dateStyle
values if that works for you. But I'd generally advise against using a hard-coded dateFormat
, but rather use a format that honors the end-user's localization settings.
Remove time from NSDate object and save it in NSDate not in string?
This is not possible to remove TimeStamp from NSDate. NSDate is always packed with timestamp.
NSDate is based on the UTC time zone. If it is 1AM in US, it will be 12:30 PM in some other country and the date will be different. It will become trouble to get who entered when if different dates are there. So to make the date consistent timestamp-ing is required.
EDIT:
UTC update as suggested by Zaph :)
tiemstamp as suggested by Daij-Djan
NSDateFormatter subtracting a day when removing time
The easiest way is to use startOfDayForDate
of NSCalendar
Swift 2:
func dateWithOutTime( datDate: NSDate) -> NSDate {
return NSCalendar.currentCalendar().startOfDayForDate(datDate)
}
Swift 3+:
func dateWithOutTime(datDate: Date) -> Date {
return Calendar.current.startOfDay(for: datDate)
}
or to adjust the time zone to UTC/GMT
Swift 2:
func dateWithOutTime( datDate: NSDate) -> NSDate {
let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)!
calendar.timeZone = NSTimeZone(forSecondsFromGMT: 0)
return calendar.startOfDayForDate(datDate)
}
Swift 3+:
func dateWithOutTime(datDate: Date) -> Date {
var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = TimeZone(secondsFromGMT: 0)!
return calendar.startOfDay(for: datDate)
}
remove time from a date like this 2016-02-10 00:00:00
okay I solved this myself
let date = "2016-02-10 00:00:00"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss"
let dateFromString : NSDate = dateFormatter.dateFromString(date)!
dateFormatter.dateFormat = "dd-MM-yyyy"
let datenew= dateFormatter.stringFromDate(dateFromString)
print(datenew)
Swift 2 - remove NSDate values in array if value is before current date
There are a few problems. The reason you are getting an error is because you cannot remove elements while iterating inside for-in block. You can filter the items with the following code:
func compareDeadline() {
let gameDictionary = NSUserDefaults.standardUserDefaults().dictionaryForKey(GAME_INFO) ?? [:]
let items = Array(gameDictionary.values)
let currentDate = NSDate()
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ssZ"
let filteredItems = items.flatMap({
guard let stringDeadline = $0["deadline"] as? String, let deadline = dateFormatter.dateFromString(stringDeadline) else {
return nil
}
return deadline
}).filter({
currentDate.compare($0) == .OrderedDescending
})
}
How to remove Optional( ) and format date in Swift
To remove the Optionnal("") indication you can use conditionnal binding like this :
if let date = game.datePlayed {
cell.textLabel?.text = "Date: \(date)"
} else {
//Here display something if no date is available
}
You could also force unwrap your variable with game.datePlayed!
but I would recommend against it
To format your date to something readable, use NSDateFormatter
like that:
let formatter = NSDateFormatter()
formatter.dateStyle = NSDateFormatterStyle.LongStyle
formatter.timeStyle = .MediumStyle
let dateString = formatter.stringFromDate(date)
You can change the dateStyle
and timeStyle
to suit your needs (choice between: .ShortStyle
, .MediumStyle
, .LongStyle
and .FullStyle
)
Additionaly you could use a custom date formatter like the following:
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd 'at' HH:mm"
let dateString = formatter.stringFromDate(date)
How to remove the timezone offset from an NSDate
It happens because you printing NSDate
object.NSDate
object encapsulates a single point in time, it is not responsible for it's string representation.
What you really need to do, is to calculate exact date you need, and then format it into NSString
.
Something like that:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
NSDate *pastDate = [[NSDate date] dateByAddingTimeInterval:seconds];
NSString *yourDateInString = [dateFormatter stringFromDate:pastDate];
NSLog(@"%@", yourDateInString);
Also, it is good practice to use NSCalendar
and NSCalendarComponents
to manipulate with dates and calculate new dates instead of just adding time interval.
Truncate NSDate (Zero-out time)
unsigned int flags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDateComponents* components = [calendar components:flags fromDate:date];
NSDate* dateOnly = [calendar dateFromComponents:components];
date
is the date you want to remove the time from.
This separates the date and time and creates a new date with the default time (00:00:00).
EDIT
To take time zone into account:
NSDate* dateOnly = [[calendar dateFromComponents:components] dateByAddingTimeInterval:[[NSTimeZone localTimeZone]secondsFromGMT]];
Related Topics
Change Color of Row Programmatically in Watchkit
How to Set a Custom Annotations for All Points Except for User Location
Do Protocols Have an Effect on The Retain Count
Can't Override UItableviewdatasource and UItableviewdelegate
Why Does a Function Have Long-Term Write Access to All of Its In-Out Parameters
Swift Casting Generic to Optional with a Nil Value Causes Fatalerror
Firebase Swift 3 Get List of Child in a Array
Parse Nested Completion Handlers
[Bool]' to 'Nil' Always Returns True - Issue in Swiftui
How to Detect Touches on UIimageview of UItableviewcell in Swift
Swift Equivalent of Unity3D Coroutines
Swift Initialization Rule Confusion
Setadvertisertrackingenabled Is Not Found in Settings Class of Fbsdk
Uiview.Animatewithduration Not Animating
Swift: Switch Statement Fallthrough Behavior
How to Add UIpickerview in UIalertcontroller
Calling C++ from Swift - What Is The Equivalent of Std::Vector<T>