Dateformatter Gives Wrong Time on Conversation

Dateformatter gives wrong time on conversation

- [NSDate description] (which is called when passing it to NSLog) always prints the date object in GMT timezone, not your local timezone. If you want an accurate string representation of the date, use a date formatter to create a correct string according to your timezone.

Getting wrong time from dateformatter

@user30646 -- see if this makes sense. Using your exact function:

func stringToDate(DateString dateString: String) -> NSDate? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyyMMddHHmmss"
dateFormatter.locale = Locale.init(identifier: "en_US_POSIX")
dateFormatter.timeZone = TimeZone(abbreviation: "EST")

if let date = dateFormatter.date(from: dateString) {
return date as NSDate?
}

return nil

}

let dateString = "20150909093700"

let returnedDate = stringToDate(DateString: dateString)

print("Date without formatting or Time Zone: [", returnedDate ?? "return was nil", "]")

let dFormatter = DateFormatter()
dFormatter.timeZone = TimeZone(abbreviation: "EST")
dFormatter.dateStyle = .full
dFormatter.timeStyle = .full

print("Result with formatting and Time Zone: [", dFormatter.string(from: returnedDate as! Date), "]")

You are getting the "correct time" ... you just think you're not because you're looking at the wrong string representation of that date/time.

Getting wrong date when converting string with timezone

// This lets us parse a date from the server using the RFC3339 format
let rfc3339DateFormatter = DateFormatter()
rfc3339DateFormatter.locale = Locale(identifier: "en_US_POSIX")
rfc3339DateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
rfc3339DateFormatter.timeZone = TimeZone(secondsFromGMT: 0)

// This string is just a human readable format.
// The timezone at the end of this string does not mean your date
// will magically contain this timezone.
// It just tells the parser what timezone to use to convert this
// string into a date which is basically just seconds since epoch.
let string = "2019-01-14T00:00:00+08:00"

// At this point the date object has no timezone
let shiftDate = rfc3339DateFormatter.date(from: string)!

// If you want to keep printing in SGT, you have to give the formatter an SGT timezone.
let printFormatter = DateFormatter()
printFormatter.dateStyle = .none
printFormatter.timeStyle = .full
printFormatter.timeZone = TimeZone(abbreviation: "SGT")!
let formattedDate = printFormatter.string(from: shiftDate)

You will notice that it prints 12am. There is nothing wrong with your code. You just misunderstand the Date object. Most people do.

Edit: I used the RFC formatter found in the Apple docs here. The result is the same if you use your formatter. And yes, as rmatty said, there are a few things wrong with your formatter (I stand corrected :))

NSDate Format outputting wrong date

NSDateFormatter use the current device timezone when it created the NSDate object. NSDate stores the date/time in GMT. Therefore by default NSLog will output the date/time in GMT+0. So, there's nothing wrong with your code. Now if you want to output the NSDate to your current timezone, your will have to use a NSDateFormatter object.

Getting wrong time while converting from NSString to NSDate When Device Time format is 24hr

Please try setting locale & timezone

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd-MMM-yyyy hh:mm a"];
[dateFormatter setLocale: [[NSLocale alloc] initWithLocaleIdentifier: @"en_US_POSIX"]];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
NSString *fromTime = [NSString stringWithFormat:@"%@",@"04-Jul-2017 01:46 PM"];
NSDate *dateFromString = [dateFormatter dateFromString:fromTime];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
NSString *setdtFrom=[dateFormatter stringFromDate:dateFromString];
NSLog(@"From DateTime %@",setdtFrom);

NSString to NSDate with format conversation issue

If the date format is fixed, what I do is below.

Replace T by space
Replace Z by blank

And then do formatting...

NSString *dateReceivedInString = @"2014-05-07T10:28:52.000Z";
dateReceivedInString = [dateReceivedInString stringByReplacingOccurrencesOfString:@"T" withString:@" "];
dateReceivedInString = [dateReceivedInString stringByReplacingOccurrencesOfString:@"Z" withString:@""];

Now do the formatting using

yyyy-MM-dd HH:mm:ss

Edit 1

If you want to work with your case, use below

yyyy-MM-dd'T'HH:mm:ss.SSSZ

Edit 2

I tried this and it is working.

NSString *dateReceivedInString = @"2014-05-07T10:28:52.000Z";
dateReceivedInString = [dateReceivedInString stringByReplacingOccurrencesOfString:@"T" withString:@" "];
dateReceivedInString = [dateReceivedInString stringByReplacingOccurrencesOfString:@"Z" withString:@""];

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSS"];
NSLog(@"ddddd====%@", [dateFormatter dateFromString:dateReceivedInString]);

Edit 3

To make working with your case use below.

NSString *dateReceivedInString = @"2014-05-07T10:28:52.000Z";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZ"];
NSLog(@"ddddd====%@", [dateFormatter dateFromString:dateReceivedInString]);

Why time zone conversation doesn't affect the figure in plotting datetime objects in matplotlib?

to get a correct localization of the time, I suggest to combine the date from your dates list with the time from your times list - assuming they belong together! otherwise, localization will most likely be incorrect for the date 1900-1-1.

import datetime as dt
from dateutil.tz import gettz

dates = [dt.datetime(2020, 8, 11),
dt.datetime(2020, 8, 9),
dt.datetime(2020, 8, 8),
dt.datetime(2020, 8, 6),
dt.datetime(2020, 8, 4),
dt.datetime(2020, 8, 3)]

times = [dt.datetime(1900, 1, 1, 22, 7, 0),
dt.datetime(1900, 1, 1, 23, 0, 0),
dt.datetime(1900, 1, 1, 21, 5, 0),
dt.datetime(1900, 1, 1, 2, 33, 0),
dt.datetime(1900, 1, 1, 2, 33, 0),
dt.datetime(1900, 1, 1, 14, 0, 0)]

loctimes = [dt.datetime.combine( # outer combine:
dt.date(1900, 1, 1), # will reset the date back to 1900-01-01
dt.datetime.combine(d.date(), t.time()) # inner combine: date from "dates" with time from "times"
.replace(tzinfo=dt.timezone.utc) # define that it's UTC
.astimezone(gettz('US/Eastern')) # change timezone to US/Eastern
.time() # use only the time part from the inner combine
) # outer combine done
for d, t in zip(dates, times)]

# loctimes
# [datetime.datetime(1900, 1, 1, 18, 7),
# datetime.datetime(1900, 1, 1, 19, 0),
# datetime.datetime(1900, 1, 1, 17, 5),
# datetime.datetime(1900, 1, 1, 22, 33),
# datetime.datetime(1900, 1, 1, 22, 33),
# datetime.datetime(1900, 1, 1, 10, 0)]

now the plot works as expected:

import matplotlib.pyplot as plt
import matplotlib.dates as mdates

fig, ax = plt.subplots()
ax.plot(dates, loctimes, "ro")
ax.yaxis.set_major_formatter(mdates.DateFormatter("%H:%M"))
plt.gca().yaxis.set_major_locator(mdates.HourLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y/%m/%d"))
plt.gca().xaxis.set_major_locator(mdates.DayLocator())
fig.autofmt_xdate()
plt.show()

Sample Image

Getting date from [NSDate date] off by a few hours

NSDate objects don't have time zones. They represent an absolute moment in time. However, when you ask one for its description (by printing it with NSLog(), e.g.), it has to pick a time zone. The most reasonable "default" choice is GMT. If you're not in GMT yourself, the date will seem to be incorrect, by the amount of your own offset.

You should always use an NSDateFormatter to create a string for display. The formatter's timezone should be set to yours, which is the default.

iOS NSDate() returns incorrect time

It doesn't return the wrong time. It returns exactly the right time. NSDate doesn't have any timezone information. Right now, my computer and your computer will report the exact same time when we call NSDate ().

NSLog displays NSDate in UTC. That's just what it displays. So if we both call NSLog right now, your computer will log the same date and time as mine. Because it is the same date and time.

If you want to process an NSDate (for example, to display the date and time to a user) you use an NSCalendar. The NSCalendar translates between NSDate, which is the same everywhere in the world, to the values that you want to display in your user interface, which will be different in London or in Kiev. If I look on my watch right now, I will see a different time than you see on your watch, and that is what NSCalendar is there for.



Related Topics



Leave a reply



Submit