how can i return a NSDate in a predefined time zone from a string
let responseString = "2015-8-17 GMT+05:30"
var dFormatter = NSDateFormatter()
dFormatter.dateFormat = "yyyy-M-dd ZZZZ"
var serverTime = dFormatter.dateFromString(responseString)
println("NSDate : \(serverTime!)")
the above code returns the time as
2015-08-16 18:30:00 +0000
The date format has to be assigned to the dateFormat property of the date formatter instead.
let date = NSDate.date()
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let str = dateFormatter.stringFromDate(date)
println(str)
This prints the date using the default time zone on the device. Only if you want the output according to a different time zone then you would add for example
Swift 3.*
dateFormatter.timeZone = NSTimeZone(name: "UTC")
Swift 4.*
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
also refer link http://www.brianjcoleman.com/tutorial-nsdate-in-swift/
how can i return a NSDate in a predefined time zone?
You can't.
An instance of NSDate does not carry any information about timezone or calendar. It just simply identifies one point in universal time.
You can interpret this NSDate object in whatever calendar you want. Swift's string interpolation (the last line of your example code) uses an NSDateFormatter that uses UTC (that's the "+0000" in the output).
If you want the NSDate's value as a string in the current user's calendar you have to explicitly set up a date formatter for that.
Swift 4.0
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
If you always have the same time zone for the input string, you can create two date formatters to output the local time zone (or a specified one):
let timeFormatterGet = DateFormatter()
timeFormatterGet.dateFormat = "h:mm a"
timeFormatterGet.timeZone = TimeZone(abbreviation: "PST")
let timeFormatterPrint = DateFormatter()
timeFormatterPrint.dateFormat = "h:mm a"
// timeFormatterPrint.timeZone = TimeZone(abbreviation: "EST") // if you want to specify timezone for output, otherwise leave this line blank and it will default to devices timezone
if let date = timeFormatterGet.date(from: "3:30 PM") {
print(timeFormatterPrint.string(from: date)). // "6:30 PM" if device in EST
} else {
print("There was an error decoding the string")
}
The number 1 means 1 regardless of language. Yet in English it's spelled as one, in Spanish it's una, in Arabic it wahid, etc.
Similarly 123982373 seconds pass 1970 is going to reflect differently in different timezones or calendar formats, but's all still 123982373 seconds passed 1970
The difference between 3 seconds and 7 seconds is 4 seconds. That doesn't require a calendar. Neither you need a calendar/timezone to know the difference in time between these two Epoch times 1585420200 and 1584729000
Dates are just a timeInterval from January 1, 1970 (midnight UTC/GMT). Dates also happen to have a string representation.
Repeating Nikolia's answer, Swift's default string interpolation (2015-08-16 18:30:00 +0000) uses a DateFormatter that uses UTC (that's the "+0000" in the output).
Calendars with the use of timezones give us a contextual representation that is just easier to understand than trying to calculate the difference between two gigantic numbers.
Meaning a single date (think of a single timeInterval since 1970) will have a different string interpretations per calendar. On top of that a calendar will itself vary based on time zones
I highly recommend that you go and play around with this Epoch converter site and see how selecting a different timezone will cause the string representations for the same moment/date/timeInterval to change
I also recommend to see this answer. Mainly this part:
Timezone is just an amendment to the timestamp string, it's not considered by the date formatter.
To consider the time zone you have to set the timeZone of the formatter
dateFormatter.timeZone = TimeZone(secondsFromGMT: -14400)
Related
I've looked around and people have had problems with different years, random and changing results, and nil dates, but nothing like what I have, so I am asking here. Note I am in Playground right now.
I am taking strings in the format of "yyyy-mm-dd" and converting them to a different date format. Here is the code:
let example = "2001-11-03"
let dateFormatterInput = ISO8601DateFormatter()
dateFormatterInput.formatOptions = [.withFullDate, .withDashSeparatorInDate]
let date = dateFormatterInput.date(from: example)
let dateFormatterOutput = DateFormatter()
dateFormatterOutput.dateFormat = "MMMM dd, yyyy"
let output = dateFormatterOutput.string(from: date!)
The sidebar in Playground shows that the first reference to the previous day's date happens on the let date line. Also, this behavior happens on every date I've tried. In this example, it returns "November 2, 2001." I've tried different months, days, and years (1900s and 2000s) and it gives me the same result every time.
What am I doing wrong?
The key thing here is that ISO8601DateFormatter by default thinks that the time zone of your date string is GMT:
ISO8601DateFormatter.timeZone:
The time zone used to create and parse date representations. When unspecified, GMT is used.
However, the timeZone of DateFormatter by default (and also the side bar of the playground) assumes your device's local time zone:
DateFormatter.timeZone
The time zone for the receiver. If unspecified, the system time zone is used.
If your system time zone has a negative UTC offset on the start of the day 2001-11-03 UTC, then when seen from your time zone, that moment is actually in the day 2001-11-02. Hence the output you see.
Assuming you don't care about the actual value of date, and just care about the final string output, you can just set the timeZone of DateFormatter to GMT:
dateFormatterOutput.timeZone = TimeZone(identifier: "GMT")
Side note: You should also set locale when using a fixed format to avoid localisation issues:
dateFormatterOutput.locale = Locale(identifier: "en_US_POSIX")
Or better, just use one of the built-in, locale sensitive formats instead:
dateFormatterOutput.dateStyle = .medium
dateFormatterOutput.timeStyle = .none
The input string will always be in the Hours:Minutes:Seconds AM/PM format, and it will always be in the UTC Timezone (The string represents the sunrise time where the user is, but only in UTC). A few examples are:
10:3:30 AM,
2:40:01 PM,
12:0:04 AM
I want to convert the time to the user's timezone and then get rid of the seconds component, so that it is just "Hours:Minutes AM/PM"
So far, I think I can use
var localTimeZoneAbbreviation: String { return TimeZone.current.abbreviation() ?? "" }
to get the user's current timezone, but I still don't know how to convert the string to that timezone. Any suggestions?
Use DateFormatter. One instance to convert from your UTC time to a Date and another to convert from that Date to a localized String.
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX") // set locale before format; good to use this locale for fixed date formats
formatter.dateFormat = "h:m:ss a"
formatter.timeZone = TimeZone(abbreviation: "UTC")
let date = formatter.date(from: "10:3:30 AM")! // whichever input string you have
let localFormatter = DateFormatter() // time zone and locale default to system's
localFormatter.dateFormat = "hh:mm a" // if you don't want a zero padding single digits then use "h:m a"
let string = localFormatter.string(from: date)
Note the day/month/year will implicitly default to the default for the system, (I'm seeing January 1 2000) but you can presumably ignore that.
I want "yyyy-MM-dd HH:mm:ss", with time in 24 hour format, but as i m having 12 hrs date format setting in my phone and Timezone is set to the Muscat ,the date which I am getting is always 12 hrs format, while i m checking with UK region. I am able to change Date() into string in 24 hrs format but while I am changing 24 hrs string into 24 hrs Date , It always give me 12 hrs Date format
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
let dateToString = dateFormatter.string(from: Date()) //2020-04-06 15:47:16
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
let dateFromString = dateFormatter.date(from: dateToString)
print(dateFromString) // 2020-04-06 1:47:25 pm +0000
A Date object just represents a point in time. The “should I show it in 12 hour clock or 24 hour clock” is not something that Date objects know about. This is a feature of strings generated by (or consumed by) a DateFormatter.
So, a few thoughts:
A date formatter’s dateFormat (and its locale) dictates what a string will look like when you call string(from:). (It will also dictate how to interpret a string and create a Date object when you call date(from:), but that’s not relevant here.)
So, if you’re looking for a string representation of a date using a 24 hour clock, look at the string generated by the date formatter’s string(from:) method. This is the dateToString string in your example.
But, if you subsequently generate a Date object from the formatter’s date(from:) method, that resulting Date will not capture whether to use 12 vs 24 hour clock. If you print this Date object, it won’t reflect your 12/24 hour clock preference.
Bottom line, only concern yourself with am/pm vs 24-hour clock when looking at String objects generated by (or passed to) the DateFormatter. Don’t worry about the format of the output when you print a Date object, as that’s for debugging purposes only and won’t capture this am/pm vs 24-hour clock dimension.
You said:
Final statement is giving me “2020-04-09 4:23:27 am +0000” format.
If you’re seeing the +0000, that suggests that you are printing the Date object, itself. The dateFormat and locale of a DateFormatter only controls the format of the string generated by string(from:) (and how strings are parsed).
So, print the string generated by DateFormatter, not Date objects. The print of a Date object will always be in this predefined format. Within the app, if you need the output in a given format, use the String generated by DateFormatter, not Date objects.
Consider a more obvious example of the issue where the DateFormatter is used to create a string in a very different format:
let now = Date()
print(now) // 2020-04-07 11:54:58 +0000
let formatter = DateFormatter()
formatter.dateStyle = .long
formatter.timeStyle = .long
let string = formatter.string(from: Date())
print(string) // April 7, 2020 at 4:54:58 AM PDT
if let date = formatter.date(from: string) {
print(date) // 2020-04-07 11:54:58 +0000
}
So, even though that formatter successfully converted a Date to a String, and back, that final print statement uses the same fixed format that the first print statement did, because I’m just printing a Date object. I’m not concerned that the that last print statement didn’t honor the configuration of my DateFormatter. I wouldn’t expect it to. When I print a Date, it’s always in that fixed, predefined format. I only worry about the format of the strings generated by the DateFormatter (the second print statement).
As an aside, there are secondary questions about your "yyyy-MM-dd HH:mm:ss" format. What timezone does this represent? Your local timezone? Your server’s timezone? GMT/UTC/Zulu? We often use ISO8601/RFC3339 date strings (like 2020-04-07T11:54:58Z) to remove this ambiguity. You should get your arms around your original question first, but when you have that behind you, you’ll want to take a hard look at why you’re storing it in this format, and how you want to deal with timezones correctly. But first things first.
I have a question about Swift type TimeZone.
I need to get a UTC0 time zone to format my Date object. I'm creating TimeZone object like this.
let utcTimeZone = TimeZone(abbreviation: "UTC")
But when created this object gives me GMT0 time zone. Is this possible to get UTC0 time zone in Swift? Also what is the difference between GMT (fixed) and GMT (GMT) offset 0 in playground?
Xcode 10.3 Playground
Technically, there are really subtle differences between UTC and GMT (GMT could mean UT1), but the designers of the API thought they are practically the same (which they are), so they made this true:
TimeZone(identifier: "UTC") == TimeZone(identifier: "GMT")
They both represent a timezone with a constant offset of 0.
If you just want to show the letters "UTC" in some output text, use a DateFormatter:
let formatter = DateFormatter()
formatter.timeZone = TimeZone(identifier: "UTC")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss 'UTC'"
print(formatter.string(from: Date()))
Or better yet, use a ISO8601DateFormatter, which adds a Z to the end of the date to indicate that the date time is in UTC:
let formatter = ISO8601DateFormatter()
formatter.timeZone = TimeZone(identifier: "UTC")
print(formatter.string(from: Date()))
Also what is the difference between GMT (fixed) and GMT (GMT) offset 0 in playground?
The former comes from the Swift TimeZone class, and the latter comes from the Objective-C NSTimeZone class. One is the bridged version of the other. From the docs of NSTimeZone,
use NSTimeZone when you need reference semantics or other Foundation-specific behavior.
I've been there, according to google
There is no time difference between Coordinated Universal Time and Greenwich Mean Time
In other words, GMT is (basically) UTC, so you already have it!
offset 0 is referring to the timezones offset from UTC/GMT, which is 0, and would be potentially something like 240 if you were in EST (depending on if it's in minutes, hours, milliseconds etc.).
fixed on your second line means it's GMT and the offset data is potentially immutable. I wouldn't know without the playground open but I'd try changing the timezone after instancing that and see how if the offset can be changed post assignment.
You can use this instead of UTC, in some device only setting UTC not working
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let date = dateFormatter.date(from: "2020-01-23T11:55:00.000Z")
i'm using xCode 7.2.1 ad Swift2, writing fo iOS.
i did a function for converting a String to a NSDate and that's :
class func StringToDateWithHour(data : String) -> NSDate
{
let dateFormatter = NSDateFormatter()
dateFormatter.timeZone = NSTimeZone(abbreviation: "CET");
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
guard let date = dateFormatter.dateFromString(data) else{
return NSDate()
}
return date
}
I don't understand why i get back the UTC time, INSTEAD of CET time.
When i try to convert a string like : "2016-2-21 10:00:00" i get back
"2016-2-21 09:00:00" , one hour less.
Thank you.
You're saying that you want to convert 10 am CET to a NSDate.
That correctly outputs 9 am UTC time (UTC is one hour behind CET time).
NSDate objects don't depend on time zones, they're just data from a particular point in time.
NSDate objects encapsulate a single point in time, independent of any particular calendrical system or time zone. Date objects are immutable, representing an invariant time interval relative to an absolute reference date (00:00:00 UTC on 1 January 2001).