DateFormater gives day before swift - swift

when I use DateFormateer it returns me a day before.
nextDayShouldBe = currectDay.addingTimeInterval(24 * 3600)
print(nextDayShouldBe) //prints (2022-07-02 21:58:11 +0000) it's right
let nextDay = nextDayShouldBe?.getFormattedDate(format: format)
try? realm.write({
userData?.nextDay = nextDay
print(nextDayShouldBe?.getFormattedDate(format: format)) // prints "01/07/2022"
})
I tried all methods to fix it (dateformatter.locale, timeZone, calendar).
extension Date {
func getFormattedDate(format: String) -> String {
let dateformat = DateFormatter()
dateformat.dateFormat = format
dateformat.timeZone = TimeZone(secondsFromGMT: 10800)
dateformat.calendar = .current
dateformat.locale = Locale.autoupdatingCurrent
return dateformat.string(from: self)
}
}
How to get 2022-07-02 ??

okey, I did it and it works:
nextDayShouldBe = currectDay.addingTimeInterval(24 * 3600)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"
let fromDateToString = dateFormatter.string(from: nextDayShouldBe!)
print(fromDateToString)

Related

Creating Date object from timestamp in Swift [duplicate]

I get a crash when running and it points at the dateFormmater.timezone.
The error in the console is:
Could not cast value of type 'Swift.Optional' (0x1192bf4a8) to 'NSTimeZone' (0x1192c0270).
the value of rowEvents.date is "1480134638.0"
Im trying to pull out a Unix timestamp from Firebase saved as a string. Convert it to Date and again save it as a string so I can post it on a cell label.
I got this code from StackOverflow. I plugged in my data and everything is all good until I run it. I guess everything is not all good...
if let lastUpdated : String = rowEvents.date {
let epocTime = TimeInterval(lastUpdated)! / 1000 // convert it from milliseconds dividing it by 1000
let unixTimestamp = NSDate(timeIntervalSince1970: epocTime) //convert unix timestamp to Date
let dateFormatter = DateFormatter()
dateFormatter.timeZone = NSTimeZone() as TimeZone!
dateFormatter.locale = NSLocale.current // NSLocale(localeIdentifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
dateFormatter.date(from: String(describing: unixTimestamp))
let updatedTimeStamp = unixTimestamp
let cellDate = DateFormatter.localizedString(from: updatedTimeStamp as Date, dateStyle: DateFormatter.Style.full, timeStyle: DateFormatter.Style.medium)
cell.subtitleLabel.text = cellDate
}
The result came from this code here:
let myTimeStamp = self.datePicker?.date.timeIntervalSince1970
let calendarDate = String(describing: myTimeStamp! /** 1000*/)
You can convert unixTimestamp to date using Date(timeIntervalSince1970:).
let unixTimestamp = 1480134638.0
let date = Date(timeIntervalSince1970: unixTimestamp)
If you want to display date in string with specific formate than you can use DateFormatter like this way.
let date = Date(timeIntervalSince1970: unixtimeInterval)
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(abbreviation: "GMT") //Set timezone that you want
dateFormatter.locale = NSLocale.current
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm" //Specify your format that you want
let strDate = dateFormatter.string(from: date)
The problem is the line dateFormatter.timeZone = NSTimeZone() as TimeZone!.
Simply use TimeZone instead of NSTimeZone like
dateFormatter.timeZone = TimeZone.current and your code will work.
You might also remove your / 1000 because 1480134638.0 looks more like seconds than milliseconds (since 1970).
Swift 4.1. I created a function. Just pass you timeStamp in function param and function will return data in string data type. You can add more properties to DateFormatter object.
func getDateFromTimeStamp(timeStamp : Double) -> String {
let date = NSDate(timeIntervalSince1970: timeStamp / 1000)
let dayTimePeriodFormatter = DateFormatter()
dayTimePeriodFormatter.dateFormat = "dd MMM YY, hh:mm a"
// UnComment below to get only time
// dayTimePeriodFormatter.dateFormat = "hh:mm a"
let dateString = dayTimePeriodFormatter.string(from: date as Date)
return dateString
}
Using playground all I did was this.
let epochTime = 1547855446
let newTime = Date(timeIntervalSince1970: TimeInterval(epochTime))
print(newTime)
Returns this - 2019-01-18 23:50:46 +0000
extension Double{
func convertDate(formate: String) -> String {
let date = (timeIntervalSince1970: self)
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone.current
dateFormatter.locale = NSLocale(localeIdentifier: "(your localization language)" ) as Locale //localization language
dateFormatter.dateFormat = formate //Specify your format that you want let
strDate = dateFormatter.string(from: date)
return strDate
}
}
//usage
let timeStamp:Double = Double(1595407043)
print(timeStamp.convertDate(formate: "EEEE dd/MM/YYY"))
This solution is valid for swift 3 -> 4.2 :
you can add an extension on the Double that returns the date formatted:
extension Double {
// returns the date formatted.
var dateFormatted : String? {
let date = Date(timeIntervalSince1970: self)
let dateFormatter = DateFormatter()
dateFormatter.timeStyle = DateFormatter.Style.none //Set time style
dateFormatter.dateStyle = DateFormatter.Style.short //Set date style
return dateFormatter.string(from: date)
}
// returns the date formatted according to the format string provided.
func dateFormatted(withFormat format : String) -> String{
let date = Date(timeIntervalSince1970: self)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
return dateFormatter.string(from: date)
}
}
example on the above :
let timeStamp = 82749029.0
print(timeStamp. dateFormatted)
//output
//12/11/1994
let timeStamp = 82749029.0
print(timeStamp. dateFormatted(withFormat : "MM-dd-yyyy HH:mm"))
//output
//12-11-1994 13:04

How convert DateTime to string

I get from server response in DateTime like this :
2019-04-24T16:25:02.557Z
and I would like only in String:
2019-04-23
How can I do this?
my code:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ssZZZ"
let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "MMM dd,yyyy"
let d = job.postedAt
if let date = dateFormatter.date(from: d) {
let k = dateFormatterPrint.string(from: date)
destinationVC.createdJob = k
} else {
print("There was an error decoding the string")
}
To convert the 2019-04-24T16:25:02.557Z to a Date object, you'd use:
let iso8601DateFormatter = ISO8601DateFormatter()
iso8601DateFormatter.formatOptions.insert(.withFractionalSeconds)
guard let date = iso8601DateFormatter.date(from: "2019-04-24T16:25:02.557Z") else { return }
And then to output only a date string in the UI, with no time, you'd use something like:
let outputFormatter = DateFormatter()
outputFormatter.dateStyle = .medium
let result = outputFormatter.string(from: date)
What about this ?
func stringFromDate(_ date: Date) -> String {
let formatter = DateFormatter()
formatter.dateFormat = "dd MMM yyyy HH:mm" //yyyy
return formatter.string(from: date)
}
Try,
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "yyyy-MM-dd"
let d = "2019-04-24T16:25:02.557Z"
if let date = dateFormatter.date(from: d) {
let k = dateFormatterPrint.string(from: date)
print(k)
} else {
print("There was an error decoding the string")
}
Your dateFormatter.dateFormat should be yyyy-MM-dd'T'HH:mm:ss.SSS'Z' and your dateFormatterPrint.dateFormat should be yyyy-MM-dd.

UTC time conversion: How do I convert an integer (UTC) into a 'datetime' time stamp? [duplicate]

My current code:
if let var timeResult = (jsonResult["dt"] as? Double) {
timeResult = NSDate().timeIntervalSince1970
println(timeResult)
println(NSDate())
}
The results:
println(timeResult) = 1415639000.67457
println(NSDate()) = 2014-11-10 17:03:20 +0000 was just to test to see what NSDate was providing.
I want the first to look like the last. The value for dt = 1415637900.
Also, how can I adjust to time zone? Running on iOS.
You can get a date with that value by using the NSDate(withTimeIntervalSince1970:) initializer:
let date = NSDate(timeIntervalSince1970: 1415637900)
To get the date to show as the current time zone I used the following.
if let timeResult = (jsonResult["dt"] as? Double) {
let date = NSDate(timeIntervalSince1970: timeResult)
let dateFormatter = NSDateFormatter()
dateFormatter.timeStyle = NSDateFormatterStyle.MediumStyle //Set time style
dateFormatter.dateStyle = NSDateFormatterStyle.MediumStyle //Set date style
dateFormatter.timeZone = NSTimeZone()
let localDate = dateFormatter.stringFromDate(date)
}
Swift 3.0 Version
if let timeResult = (jsonResult["dt"] as? Double) {
let date = Date(timeIntervalSince1970: timeResult)
let dateFormatter = DateFormatter()
dateFormatter.timeStyle = DateFormatter.Style.medium //Set time style
dateFormatter.dateStyle = DateFormatter.Style.medium //Set date style
dateFormatter.timeZone = self.timeZone
let localDate = dateFormatter.string(from: date)
}
Swift 5
if let timeResult = (jsonResult["dt"] as? Double) {
let date = Date(timeIntervalSince1970: timeResult)
let dateFormatter = DateFormatter()
dateFormatter.timeStyle = DateFormatter.Style.medium //Set time style
dateFormatter.dateStyle = DateFormatter.Style.medium //Set date style
dateFormatter.timeZone = .current
let localDate = dateFormatter.string(from: date)
}
It's simple to convert the Unix timestamp into the desired format. Lets suppose _ts is the Unix timestamp in long
let date = NSDate(timeIntervalSince1970: _ts)
let dayTimePeriodFormatter = NSDateFormatter()
dayTimePeriodFormatter.dateFormat = "MMM dd YYYY hh:mm a"
let dateString = dayTimePeriodFormatter.stringFromDate(date)
print( " _ts value is \(_ts)")
print( " _ts value is \(dateString)")
For managing dates in Swift 3 I ended up with this helper function:
extension Double {
func getDateStringFromUTC() -> String {
let date = Date(timeIntervalSince1970: self)
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US")
dateFormatter.dateStyle = .medium
return dateFormatter.string(from: date)
}
}
This way it easy to use whenever you need it - in my case it was converting a string:
("1481721300" as! Double).getDateStringFromUTC() // "Dec 14, 2016"
Reference the DateFormatter docs for more details on formatting (Note that some of the examples are out of date)
I found this article to be very helpful as well
Here is a working Swift 3 solution from one of my apps.
/**
*
* Convert unix time to human readable time. Return empty string if unixtime
* argument is 0. Note that EMPTY_STRING = ""
*
* #param unixdate the time in unix format, e.g. 1482505225
* #param timezone the user's time zone, e.g. EST, PST
* #return the date and time converted into human readable String format
*
**/
private func getDate(unixdate: Int, timezone: String) -> String {
if unixdate == 0 {return EMPTY_STRING}
let date = NSDate(timeIntervalSince1970: TimeInterval(unixdate))
let dayTimePeriodFormatter = DateFormatter()
dayTimePeriodFormatter.dateFormat = "MMM dd YYYY hh:mm a"
dayTimePeriodFormatter.timeZone = NSTimeZone(name: timezone) as TimeZone!
let dateString = dayTimePeriodFormatter.string(from: date as Date)
return "Updated: \(dateString)"
}
func timeStringFromUnixTime(unixTime: Double) -> String {
let date = NSDate(timeIntervalSince1970: unixTime)
// Returns date formatted as 12 hour time.
dateFormatter.dateFormat = "hh:mm a"
return dateFormatter.stringFromDate(date)
}
func dayStringFromTime(unixTime: Double) -> String {
let date = NSDate(timeIntervalSince1970: unixTime)
dateFormatter.locale = NSLocale(localeIdentifier: NSLocale.currentLocale().localeIdentifier)
dateFormatter.dateFormat = "EEEE"
return dateFormatter.stringFromDate(date)
}
In Swift 5
Using this implementation you just have to give epoch time as a parameter and you will the output as (1 second ago, 2 minutes ago, and so on).
func setTimestamp(epochTime: String) -> String {
let currentDate = Date()
let epochDate = Date(timeIntervalSince1970: TimeInterval(epochTime) as! TimeInterval)
let calendar = Calendar.current
let currentDay = calendar.component(.day, from: currentDate)
let currentHour = calendar.component(.hour, from: currentDate)
let currentMinutes = calendar.component(.minute, from: currentDate)
let currentSeconds = calendar.component(.second, from: currentDate)
let epochDay = calendar.component(.day, from: epochDate)
let epochMonth = calendar.component(.month, from: epochDate)
let epochYear = calendar.component(.year, from: epochDate)
let epochHour = calendar.component(.hour, from: epochDate)
let epochMinutes = calendar.component(.minute, from: epochDate)
let epochSeconds = calendar.component(.second, from: epochDate)
if (currentDay - epochDay < 30) {
if (currentDay == epochDay) {
if (currentHour - epochHour == 0) {
if (currentMinutes - epochMinutes == 0) {
if (currentSeconds - epochSeconds <= 1) {
return String(currentSeconds - epochSeconds) + " second ago"
} else {
return String(currentSeconds - epochSeconds) + " seconds ago"
}
} else if (currentMinutes - epochMinutes <= 1) {
return String(currentMinutes - epochMinutes) + " minute ago"
} else {
return String(currentMinutes - epochMinutes) + " minutes ago"
}
} else if (currentHour - epochHour <= 1) {
return String(currentHour - epochHour) + " hour ago"
} else {
return String(currentHour - epochHour) + " hours ago"
}
} else if (currentDay - epochDay <= 1) {
return String(currentDay - epochDay) + " day ago"
} else {
return String(currentDay - epochDay) + " days ago"
}
} else {
return String(epochDay) + " " + getMonthNameFromInt(month: epochMonth) + " " + String(epochYear)
}
}
func getMonthNameFromInt(month: Int) -> String {
switch month {
case 1:
return "Jan"
case 2:
return "Feb"
case 3:
return "Mar"
case 4:
return "Apr"
case 5:
return "May"
case 6:
return "Jun"
case 7:
return "Jul"
case 8:
return "Aug"
case 9:
return "Sept"
case 10:
return "Oct"
case 11:
return "Nov"
case 12:
return "Dec"
default:
return ""
}
}
How to call?
setTimestamp(epochTime: time) and you'll get the desired output as a string.
Convert timestamp into Date object.
If timestamp object is invalid then return current date.
class func toDate(_ timestamp: Any?) -> Date? {
if let any = timestamp {
if let str = any as? NSString {
return Date(timeIntervalSince1970: str.doubleValue)
} else if let str = any as? NSNumber {
return Date(timeIntervalSince1970: str.doubleValue)
}
}
return nil
}
Swift:
extension Double {
func getDateStringFromUnixTime(dateStyle: DateFormatter.Style, timeStyle: DateFormatter.Style) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = dateStyle
dateFormatter.timeStyle = timeStyle
return dateFormatter.string(from: Date(timeIntervalSince1970: self))
}
}
Anyway #Nate Cook's answer is accepted but I would like to improve it with better date format.
with Swift 2.2, I can get desired formatted date
//TimeStamp
let timeInterval = 1415639000.67457
print("time interval is \(timeInterval)")
//Convert to Date
let date = NSDate(timeIntervalSince1970: timeInterval)
//Date formatting
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd, MMMM yyyy HH:mm:a"
dateFormatter.timeZone = NSTimeZone(name: "UTC")
let dateString = dateFormatter.stringFromDate(date)
print("formatted date is = \(dateString)")
the result is
time interval is 1415639000.67457
formatted date is = 10, November 2014 17:03:PM
If you are maximizing the Codable protocol for parsing your JSON data. You could simply make the data type of dt as Date and do:
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .secondsSince1970
For me: Converting timestamps coming from API to a valid date :
`let date = NSDate.init(fromUnixTimestampNumber: timesTamp /* i.e 1547398524000 */) as Date?`
By using this code you will be able to convert timeStamp to Time and Date
let timeStamp = Date().timeIntervalSince1970
let date = NSDate(timeIntervalSince1970: timeStamp)
let dayTimePeriodFormatter = DateFormatter()
dayTimePeriodFormatter.dateFormat = "dd MMMM,YYYY.hh:mm a"
let dateTimeString = dayTimePeriodFormatter.string(from: date as Date)
let dateTime = dateTimeString.split(separator: ".")
print( "Date = \(dateTime[0])")
print( "Time = \(dateTime[1])")
Output:
Date = 19 January,2022
Time = 10:46 AM

swift 4 Date from from ISO string to custom format?

I have ISO date from API I want to convert it to another custom date format, I've checked some threads here it's look like I have to use the extension on Date class, unfortunately, all my attempts failed.
this example for date i have :
2014-10-22T00:00:00+00:00
I want to convert it to July 2014
can I use normal Date class to do it?
and below what I am trying to do
let formatter = ISO8601DateFormatter()
let date = formatter.date(from: "2016-08-26T12:39:00Z")
let string = formatter.string(from: Date())
Try it:
let formatter = ISO8601DateFormatter()
if let date = formatter.date(from: "2014-10-22T00:00:00+00:00") {
let string = date.stringDate
print(string) // October 2014
}
extension Date {
var stringDate: String {
let formatter = DateFormatter()
formatter.dateFormat = "MMMM yyyy"
return formatter.string(from: self)
}
}
my Date load from SQL Server and format like this "2018-01-17T03:08:28.158769" the code below is work for me perfectly
let isoDate = "2018-01-17T03:08:28.158769"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSS"
let date = dateFormatter.date(from:isoDate!)!
dateFormatter.dateFormat = "d.MMMM.YYYY"
let displayDate = dateFormatter.string(from: date)
displayDateInLabel.text = displayDate
result
17.January.2018
You can get Month and Year like this
override func viewDidLoad() {
super.viewDidLoad()
print(getFormattedDate(date: Date()))
}
func getFormattedDate(date: Date) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM YYYY"
let strMonth = dateFormatter.string(from: date)
return strMonth
}

Convert string with timezone to date

I have this type of string and want to convert it to date
"2017-05-27T00:00:00.000+0400"
but none of this formatters convert it to date
"yyyy-MM-dd'T'HH:mm:SSSZ"
"yyyy-MM-dd'T'HH:mm:SSSX"
Your forgot to add ss for seconds so correct formate should be yyyy-MM-dd'T'HH:mm:ss.SSSZ
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let date = dateFormatter.date(from: "2017-05-27T00:00:00.000+0400")
Your error was that the seconds were missing. So the right format should be: yyyy-MM-dd'T'HH:mm:ss.SSSZ. You can also use an extension for this purpose:
extension String {
var toCustomDate: Date {
return Date.Formatter.customDate.date(from: self)!
}
}
extension Date {
struct Formatter {
static let customDate: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
return formatter
}()
}
var customDate: String {
return Formatter.customDate.string(from: self)
}
}
let str = "2017-05-27T00:00:00.000+0400"
let date = str.toCustomDate
If you have more date formats, then just add them to the extensions.
you can do like this
let dateString = "2017-05-27T00:00:00.000+0400"
let formachanger = DateFormatter()
formachanger .dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
if let dateFromString = formachanger .date(from: dateString) {
formachanger .dateFormat = "yyyy-MM-dd HH:mm"
let stringFromDate = formachanger .string(from: dateFromString)
}
try this function
func getGMTDateFrom(String string : String) -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEE, dd MMM yyyy hh:mm:ss zz"
let dateObj = dateFormatter.date(from: string)
return dateObj
}
Change date format according to your need.