How can I convert string like (2019-11-02) without time to date format and get current Date device without time then compare with together?
As well as the above using string representations of date, you can actually work with just the dates themselves. Just converting a the string will give you a "start of day" date. The Calendar has a method which will do the same with a date, allowing you to compare the converted string to 'today'
func isDateToday(dateString: String) -> Bool {
let df = DateFormatter()
df.dateFormat = "yyyy-MM-dd"
let date = df.date(from: dateString)
let today = Calendar.current.startOfDay(for: Date())
return date == today
}
You can convert the string to date using a dateFormatter then compare with the current date using an if statement
import Foundation
//convert string to date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let myDate = dateFormatter.date(from: "2019-11-02")
//convert today's date in the same formate
let currentFormatter = DateFormatter()
currentFormatter.dateStyle = .short
currentFormatter.dateFormat = "yyyy-MM-dd"
let today = currentFormatter.string(from: Date())
let todayDate = dateFormatter.date(from: today)
//Compare the two date's
if myDate == todayDate {
print("ok")
}
Related
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
I get a date from sever like that: "2020-07-20T23:03:11.17926"
I think to make it readable, I have to convert it to timestamp, then convert it to a readable string again.
Here is my code:
func timeStringFromUnixTime(timestamp: String) -> String {
let stringDate = timestamp
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let dateString = dateFormatter.date(from: stringDate)
//get timestamp from Date
if let dateTimeStamp = dateString?.timeIntervalSince1970 {
let date = Date(timeIntervalSince1970: TimeInterval(dateTimeStamp))
dateFormatter.dateFormat = "MMM d, h:mm"
dateFormatter.timeZone = TimeZone(identifier: NSTimeZone.default.identifier)
let localDate = dateFormatter.string(from: date)
return localDate
}
return ""
}
But the problem is, dateString will be equal to nil, so it returns a empty string. Could anyone help me on this?
Replace:
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
with:
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"
Z - "RFC 822 GMT format. Can also match a literal Z for Zulu (UTC) time."
SSS - "The milliseconds."
Take a look at NSDateFormatter.com to see more about date formatting.
I'm getting date as a sting format from API (2019-11-22), I want to compare this date with current date.
I tried converting current date as string format this is success but this is not satisfying requiremet. I have to convert to String(2019-11-22) to Date and then I can compare two dates.
How can I convert string (2019-11-22) to Date to compare with system date pls help I'm lead knowledge in dates. Thanks in advance.
extension Date {
static func getCurrentDate() -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
return dateFormatter.string(from: Date())
}
}
if Date() < apiEach["ExpiryDate"]! as! Date{
//apiEach["ExpiryDate"]! is 2019-11-22
pritn("You can proceed it's not outdated")
}
apiEach["ExpiryDate"] is a string (apiEach["ExpiryDate"] as! Date will crash) so you have two options:
Convert the current date to string
if Date.getCurrentDate() < apiEach["ExpiryDate"] as! String { ...
Convert the API string to Date and compare that
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd"
if let apiDate = dateFormatter.date(from: apiEach["ExpiryDate"] as! String),
Date() < apiDate { ...
func minimumDate(result:String) -> Bool {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let myDate = dateFormatter.date(from: "\(result)")
dateFormatter.dateFormat = "yyyy-MM-dd"
let now = Date()
let startDateComparisionResult:ComparisonResult = now.compare(myDate!)
if startDateComparisionResult == ComparisonResult.orderedAscending {
print("Current date is smaller than end date.")
let somedateString = dateFormatter.string(from: myDate!)
print(somedateString)
return true
}
else if startDateComparisionResult == ComparisonResult.orderedDescending {
// Current date is greater than end date.
print("Current date is greater than end date.")
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let date1String = dateFormatter.string(from: myDate!)
let date2String = dateFormatter.string(from: now)
if date1String == date2String {
print("Equal date")
return true
}
return false
}
else if startDateComparisionResult == ComparisonResult.orderedSame {
// Current date and end date are same
print("Current date and end date are same")
return true
}
return true
}
Since the date format "yyyy-MM-dd" can be properly sorted/compared you can either convert current date to a string and compare it with your API value
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let now = dateFormatter.string(from: Date())
switch now.compare(input) { //input is from API
case .orderedSame:
print("Same")
case .orderedAscending:
print("Before")
case .orderedDescending:
print("After")
}
If you want to compare dates it is important that Date() will also include the current time while a date converted using a date formatter with a date only format will have its time zeroed out (midnight) so the comparison might not be correct if the date part is the same. To handle this it is better to use DateComponents
let calendar = Calendar.current
guard let date = dateFormatter.date(from: input) else { return //or error }
let components = calendar.dateComponents([.year, .month, .day], from: now, to: date)
if let year = components.year, let month = components.month, let day = components.day {
switch (year + month + day) {
case 0: // all values are zero
print("Same")
case ..<0 : // values will be zero or negative so sum is negative
print("After")
default: // values will be zero or positive so sum is positive
print("Before")
}
}
I have two different date formats from the API for the same object one is "yyyy-MM-dd" and other one is "dd-MM-YYYY" how to differentiate, that object contains specific format.
Use this may be worked for you.
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd" // YOUR DATE FORMATE
if let date = formatter.date(from: dateString) {
// IT CONTAIN YOUR DATE FORMATE
}
Try this,
let datestring = "2019-06-13" // try 13-06-2019 as well
let dateformatter = DateFormatter()
dateformatter.dateFormat = "yyyy-MM-dd"
var date = dateformatter.date(from: datestring)
if date == nil {
dateformatter.dateFormat = "dd-MM-yyyy"
date = dateformatter.date(from: datestring)
}
print(date!)
there should be many other ways to this and hope this will help to you.
You don't need to worry about whatever the format is, You just need to populate it into Date Object by using date formatter. After that you can use that Date Object where ever you want to use. Like
let datestring = "2019-06-13"
let dateformatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
var date1 = formatter.date(from: dateString)
and for other type of date
let dateString = "13-06-2019"
let dateformatter = DateFormatter()
formatter.dateFormat = "dd-MM-yyyy"
var date2 = formatter.date(from: dateString)
Now you got 2 date objects date1 & date2, use these in your code without bothering about their previous formats.
I'm trying to convert String date to local timeZone date then convert it back to Date with my current timeZone first method is working well:
let date = convertToLocalTimeZone(dateStr:"2018-05-30T14:13:20.000Z")
print(date)
the following is printed which is right:
2018-05-30 16:13GMT+2
let newDate = convertStringToDate(dateStr:date)
print(newDate)
//Converted back to UTC Time Zone :(
2018-05-30 14:13:00 +0000
func convertToLocalTimeZone(dateStr:String)->String{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:sss.SSSZ"
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
let date = dateFormatter.date (from: dateStr)
dateFormatter.timeZone = TimeZone(secondsFromGMT: getSecondsFromGMT())
dateFormatter.dateFormat = "yyyy-MM-dd HH:mmz"
let strVal = dateFormatter.string(from: date!)
return strVal
}
The problem happens when i try to convert the new String date with my local timeZone to date it returns wrong timeZone:
func convertStringToDate(dateStr:String)->Date{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mmz"
// dateFormatter.timeZone = TimeZone(abbreviation: "GMT+2")
let date = dateFormatter.date (from: dateStr)
let calendar = Calendar.current
let components = calendar.dateComponents([.year, .month, .day, .hour], from: date!)
let finalDate = calendar.date(from:components)
return finalDate!
}
Any Help will be much appreciated
I think your code is alright. You just have to understand that Date represents a point in time. It does not know anything about time zones. Time zones appears only when you format the date, so only in a String will you ever see a time zone. No matter how you create a Date, you are going to see it end up in UTC when it is printed directly.
So if you want to show a date in a time zone, format it, just like you did in convertToLocalTimeZone.
If you want, you could create your own date with a Date and a TimeZone:
struct ZonedDate: CustomStringConvertible {
var date: Date
var timeZone: TimeZone
var description: String {
// format the date using timeZone here...
}
}