Converting String to NSDate Giving Wrong Date
You are using the wrong format. You need dd MMM yyyy
.
incorrect string to date conversion swift 3.0
Your date string does not specify a year, which is therefore
determined from the default date. What you can do is to set the
default date to the (start of the) current day:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd hh:mm aa"
dateFormatter.defaultDate = Calendar.current.startOfDay(for: Date())
if let dateCompleted = dateFormatter.date(from: "10/24 12:00 PM") {
print(dateCompleted) // 2017-10-24 10:00:00 +0000
}
(I am in the Europe/Berlin timezone, therefore 12:00 PM is printed
as 10:00 GMT.)
NSDateFormater stringFromDate to dateFromString return wrong date
I found that my format is wrong from answer objective-c - NSDateFormatter returns wrong date
and reference by http://nsdateformatter.com .
It should be "yyyy" instead of "YYYY"
NsDate formatter giving wrong Date from String
The results are formated for GMT output - i.e. if you are 5:3 hours away from GMT.
You need to specify a timezone if you want the date formated to be returned in that timezone: (that is what the +0000 means)
- (NSDate *)dateFromString:(NSString *)date
{
static NSDateFormatter *dateFormatter;
if (!dateFormatter)
{
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
}
NSLog(@"Date: %@ Formatted: %@",date,[dateFormatter dateFromString:date]);
return [dateFormatter dateFromString:date];
}
NSDate() or Date() shows the wrong time
NSDate (or Date in Swift ≥ V3) does not have a time zone. It records an instant in time all over the world.
Internally, date objects record the number of seconds since the "epoch date", or Midnight on January 1, 2001 in Greenwich Mean Time, a.k.a UTC.
We normally think of dates in our local time zone.
If you log a date using
print(NSDate())
The system displays the current date, but it expresses it in UTC/Greenwich Mean Time. So the only place the time will look correct is in that time zone.
You get the same issue in the debugger if you issue the debugger command
e NSDate()
This is a pain. I personally wish iOS/Mac OS would display dates using the user's current time zone, but they don't.
EDIT #2:
An improvement on my previous use of localized string that makes it a little easier to use is to create an extension to the Date
class:
extension Date {
func localString(dateStyle: DateFormatter.Style = .medium, timeStyle: DateFormatter.Style = .medium) -> String {
return DateFormatter.localizedString(from: self, dateStyle: dateStyle, timeStyle: timeStyle)
}
}
That way you can just use an expression like Date().localString()
, or if you want to only print the time, you can use Date().localString(dateStyle:.none)
EDIT:
I just discovered that NSDateFormatter
(DateFormatter
in Swift 3) has a class method localizedString. That does what my extension below does, but more simply and cleanly. Here is the declaration:
class func localizedString(from date: Date, dateStyle dstyle: DateFormatter.Style, timeStyle tstyle: DateFormatter.Style) -> String
So you'd simply use
let now = Date()
print (DateFormatter.localizedString(
from: now,
dateStyle: .short,
timeStyle: .short))
You can pretty much ignore everything below.
I have created a category of the NSDate class (Date in swift 3) that has a method localDateString that displays a date in the user's local time zone.
Here is the category in Swift 3 form: (filename Date_displayString.swift)
extension Date {
@nonobjc static var localFormatter: DateFormatter = {
let dateStringFormatter = DateFormatter()
dateStringFormatter.dateStyle = .medium
dateStringFormatter.timeStyle = .medium
return dateStringFormatter
}()
func localDateString() -> String
{
return Date.localFormatter.string(from: self)
}
}
And in Swift 2 form:
extension NSDate {
@nonobjc static var localFormatter: NSDateFormatter = {
let dateStringFormatter = NSDateFormatter()
dateStringFormatter.dateStyle = .MediumStyle
dateStringFormatter.timeStyle = .MediumStyle
return dateStringFormatter
}()
public func localDateString() -> String
{
return NSDate.localFormatter.stringFromDate(self)
}
}
(If you prefer a different date format it's pretty easy to modify the format used by the date formatters. It's also straightforward to display the date and time in any timezone you need.)
I would suggest putting the appropriate Swift 2/Swift 3 version of this file in all of your projects.
You can then use
Swift 2:
print(NSDate().localDateString())
Swift 3:
print(Date().localDateString())
NSDateFormatter return incorrect date from string
The +0000
at the end of the date indicates GMT. All dates are stored relative to GMT; when you convert a date to a string or vice versa using a date formatter, the offset to your time zone is included. You can use NSDateFormatter's -setTimeZone:
method to set the time zone used.
In short, you're not doing anything wrong in your code. Use [df stringFromDate:date];
to see that the date is correct. (You can also use NSDate's -descriptionWithCalendarFormat:timeZone:locale:
.)
NSDateFormatter showing wrong date in ios?
Your local time zone is presumably UTC+5:30. You are specifying a date but not a time, so the time is implied to be midnight. Midnight on the 16th in your local time zone is 18:30 the day before (the 15th) in UTC time, which is why you get "2016-03-15 18:30:00 +0000"
When you log the date with NSLog(@"%@----",dateValue)
you are actually invoking [dateValue description]
, which displays the date using UTC.
You can use NSLog(@"%@----",[dateValue descriptionWithCalendarFormat:nil timeZone:[NSTimeZone localTimeZone] locale:nil])
and you will see the date in your current time zone.
Be aware though that the description
and associated methods such as descriptionWithCalendarFormat
methods are only for debugging, you should use an NSDateFormatter to convert dates to strings. iOS_Binod's answer shows one way you could do this.
NSDateFormatter return wrong date + Swift
When you convert from string to NSDate, if you do not set the timezone to the formatter, you will get the NSDate of a date in your local time zone. I suppose that your time zone is GMT+3 .
Then, when you show the value of 'date' (using println, NSLog but not NSDateFormatter), without setting the time zone, you will get GMT+0 time. That why you got 3h later.
Depend on how to use NSDateFormatter, you will have the date string as you want. In your case, It returns what you want, doesn't it?
Remember that NSDate presents a moment of time.
let dateString = "2016-04-02"
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
println("dateString: \(dateString)")
formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
let date = formatter.dateFromString(dateString) //without specify timezone, your dateString "2016-04-02" is your local time (GMT-3),
//means it's 2016-04-02 00:00:000 at GMT+0. That is the value that NSDate holds.
println("date: \(date)") //that why it show 2016-04-01 21:00:000, but not 2016-04-02 00:00:000
formatter.dateFormat = "yyyy-MM-dd"
let formattedDateString = formatter.stringFromDate(date!)
println("formattedDateString: \(formattedDateString)")
Related Topics
Multiple Lines in UItabbaritem Label
How to Make a Reusable Tableview for Different Screens in the Same Application
CSS Flexible Box Layout on Ipad
Xcode 8/Swift 3 and Installing Apps on iPhone 4 Running iOS 7
Go Back to View Controller from Skscene
Added a Custom Framework, Now Swift Can't Unarchive Data
Populating Input Text Field in Wkwebview
Google Signin Not Calling Delegate Method After Success
Customize Google Maps Blue Dot for Current Location
How to Use Third Party Lib in Embedded Dynamic Framework for iOS with Swift
Uipageviewcontroller Setviewcontrollers, UIpagecontrol Not Showing Right Current Number
Add 'For...In' Support to a Class in Swift 2
Terminating App Due to Uncaught Exception 'Nsinvalidargumentexception' - iOS Google Sign In
Swiftui - How to Blur the Default Background Color of a View
How to Queue Multiple Accessibility Notifications for Voiceover
Play Keyboard Click Sound in a Collection View Controller
Simulator Vs Physical Device: Navigationlink Broken After One Use