This question already has answers here:
Swift 3 - Comparing Date objects
(14 answers)
Closed 3 years ago.
I want to check today's date with some other date which is in String, if both are equals then need to perform some tasks.
I tried date1 < date2 but it is comparing date, I want equal check
Dates are complicated... let Apple do it for you... Calendar date comparison
let date1 = // some date
let date2 = // some date
let isSameDay = Calendar.current.isDate(date1, equalTo: date2, toGranularity: .day)
let isSameHour = Calendar.current.isDate(date1, equalTo: date2, toGranularity: .hour)
let isSameMonth = Calendar.current.isDate(date1, equalTo: date2, toGranularity: .month)
etc...
This will work no matter which time zone, which calendar type is being used, etc...
compare both date string like,
if date1.stringWithFormatter(dateFormat: "yyyy-MM-dd") == Date().stringWithFormatter(dateFormat: "yyyy-MM-dd") {
// today's date
}else{
// not today's date
}
extension Date {
func stringWithFormatter(dateFormat: String) -> String {
let formatter: DateFormatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = dateFormat
return formatter.string(from: self)
}
func datefromString(string:String,dateFormat: String) -> Date {
let formatter: DateFormatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = dateFormat
return formatter.date(from: string)!
}
}
Use below code to check equal dates
func getCurrentDate() -> String {
let date = Date()
let formatter = DateFormatter()
formatter.dateFormat = "dd.MM.yyyy"
let result = formatter.string(from: date)
print(result)
return result
}
Now check with your date
if self.getCurrentDate() == "01.01.2001" {
\\Your stuff to be added
print("Date found!!!")
}
Related
I have got a date in this format..
2019-12-16 18:30:00 +0000
This is the code I have for that..
var utcTime = "\(dic["dueDate"]!)"
self.dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
self.dateFormatter.locale = Locale(identifier: "en_US")
let date = self.dateFormatter.date(from:utcTime)!
print(date)
I wanted to extract month and date from this string. i.e. from the above date string, I want 'December' & '16' separately.
There are several ways to get the expected result, as an option you can use this code with Calendar:
let utcTime = "2020-01-17T22:01:00"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
dateFormatter.locale = Locale(identifier: "en_US")
if let date = dateFormatter.date(from:utcTime) {
let monthInt = Calendar.current.component(.month, from: date)
let dayInt = Calendar.current.component(.day, from: date)
let monthStr = Calendar.current.monthSymbols[monthInt-1]
print(monthStr, dayInt)
}
Welcome to stack overflow.
You can try this :
let calendar = Calendar.current
calendar.component(.year, from: date)
calendar.component(.month, from: date)
calendar.component(.day, from: date)
Hope it helps...
Welcome to stack overflow. Please try this.
func getMonthAndDate(dateString: String) ->(month:String , day:String) {
guard let date = Date.getMonthAndDate(from: dateString, with: "yyyy-MM-dd'T'HH:mm:ss") else {
return ("","")
}
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM"
let month = dateFormatter.string(from: date)
dateFormatter.dateFormat = "dd"
let day = dateFormatter.string(from: date)
return (month,day)
}
extension Date {
static func getMonthAndDate(from str: String, with formatter: String) -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone.current//(abbreviation: "GMT") //Set timezone that you want
dateFormatter.locale = NSLocale.current
dateFormatter.dateFormat = formatter //Specify your format that you want
return dateFormatter.date(from: str)
}
}
Swift 5
Here is the extension you need It returns tuple having Month and date as you wanted to have
extension Date {
func getMonthAndDate() ->(month:String , day:String) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM"
let month = dateFormatter.string(from: self)
dateFormatter.dateFormat = "dd"
let day = dateFormatter.string(from: self)
return (month,day)
}
}
I give you example of month u can get date and month value separately ,
visit link for your format http://userguide.icu-project.org/formatparse/datetime
extension Date {
var month: String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM"
return dateFormatter.string(from: self)
}
}
you can use it in this way:
let date = Date()
let monthString = date.month
try same thing for date, I hope it will work for you... :)
this is an example from your code. I have stored month and day in separate string to show you. You can change according to your requirements.
var utcTime = "2019-12-16 18:30:00 +0000"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss z"
dateFormatter.locale = Locale(identifier: "en_US")
let date = dateFormatter.date(from:utcTime)!
print(date) //2019-12-16 18:30:00 +0000
dateFormatter.dateFormat = "MMMM"
let strMonth = dateFormatter.string(from: date)
print(strMonth) //December
dateFormatter.dateFormat = "dd"
let strDay = dateFormatter.string(from: date)
print(strDay) //16
Also you can use Calendar object to get date, month (gives you in digit) and year.
var utcTime = "2019-12-16 18:30:00 +0000"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss z"
dateFormatter.locale = Locale(identifier: "en_US")
let date = dateFormatter.date(from:utcTime)!
let calendarDate = Calendar.current.dateComponents([.day, .year, .month], from: date)
let day = calendarDate.day
print(day) //16
let month = calendarDate.month
print(month) //12
let year = calendarDate.year
print(year) //2019
You can get the day, month and year as follows
let yourDate = Calendar.current.dateComponents([.day, .year, .month], from: Date())
if let day = yourDate.day, let month = yourDate.month, let year = yourDate.year {
let monthName = Calendar.current.monthSymbols[month - 1]
// your code here
}
extension String {
func getMonthDay() -> (Int,Int) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ssZ"
let date = dateFormatter.date(from: self) ?? Date()
let calendar = Calendar.current
let month = calendar.component(.month, from: date)
let day = calendar.component(.day, from: date)
return (month, day)
}
}
I have code like this:
func getCurrentDate() -> Date {
let formatter = DateFormatter()
formatter.dateStyle = DateFormatter.Style.medium
formatter.timeStyle = DateFormatter.Style.none
formatter.dateFormat = "dd.MM.yyyy"
formatter.timeZone = TimeZone(identifier: "GMT")
//I want for currentDate would be a Date type
let currentDate = formatter... /// how to convert to date type?
return currentDate
}
How to return formatted current date? Date function return date in this format: 2019-02-24 12:04:13 +0000. But I want to get date in that format: 24.02.2019.
I need a Date type for this code:
let differenceOfDate = Calendar.current.dateComponents(Set<Calendar.Component>([.day]),
from: getDateFromString(foodDate: getCurrentDateString()),
to: foodShelfLife).day
In that code I get String date and convert it to Date type! I want to get Date type in 1 function.
Why not call the calendar function like this
let differenceOfDate = Calendar.current.dateComponents(Set<Calendar.Component>([.day]),
from: Date(),
to: foodShelfLife).day
Old solution
You need to change your func to return a String (or perform the formatting at a later stage)
func getCurrentDate() -> String {
let formatter = DateFormatter()
formatter.dateFormat = "dd.MM.yyyy”
formatter.locale = Locale(identifier: "en_POSIX_US")
return formatter.string(from: Date())
}
If I am not mistaking, there is a misunderstanding here.
Date has nothing to do with how to display it (the format). Mentioning that:
Date function return date in this format: 2019-02-24 12:04:13 +0000.
is the result of printing Date():
print(Date())
If you want to see it as "24.02.2019", then you should edit its format, therefore getCurrentDate should return a string instead:
func getCurrentDate() -> String {
let formatter = DateFormatter()
formatter.dateStyle = DateFormatter.Style.medium
formatter.timeStyle = DateFormatter.Style.none
formatter.dateFormat = "dd.MM.yyyy"
formatter.timeZone = TimeZone(identifier: "GMT")
let currentDate = formatter.string(from: Date())
return currentDate
}
Therefore:
print(getCurrentDate())
should give you the result of 24.02.2019.
Update:
If you are aiming to work with dateComponents, you should deal with dates without caring about formatting them. Example:
let yesterday = Calendar.current.date(byAdding: .day, value: -1, to: Date())!
let components = Calendar.current.dateComponents(Set<Calendar.Component>([.day]), from: yesterday, to: Date())
print(components) // day: 1 isLeapMonth: false
I want to Convert string of format "19-07-2018 08:10:24" in date time format. If the date is today then it should be "02:12 am". If the date is of yesterday then it should be like "Yesterday". Otherwise it should be in "DD/MM/yy" format. Currently I am having the time and date in string formate.
I want the final answer in string type. If the answer is "DD/MM/YY", then it should be in string format.
Use the Calendar date functions:
func format(date: Date) -> String {
let calendar = Calendar.current
if calendar.isDateInToday(date) {
// process your "Today" format
return ...
}
if calendar.isDateInYesterday(date) {
// process your "Yesterday" format
return ...
}
if calendar.isDateInTomorrow(date) {
// process your "Tomorrow" format
return ...
}
// process your "full date/time format"
return ...
}
You can read more about the Calendar functions here: https://developer.apple.com/documentation/foundation/calendar
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy HH:mm:ss"//19-07-2018 08:10:24
let date = dateFormatter.date(from: "15-07-2018 08:10:24")
dateFormatter.dateFormat = "dd/MM/yyyy"
let startDate = dateFormatter.string(from: date!)
let dateToday = (Calendar.current as NSCalendar).date(byAdding: .day, value: 0, to: Date(), options: [])! as Date
dateFormatter.dateFormat = "dd/MM/yyyy"
let strdateToday = dateFormatter.string(from: dateToday1)
let dateYesterday = (Calendar.current as NSCalendar).date(byAdding: .day, value: -1, to: Date(), options: [])! as Date
dateFormatter.dateFormat = "dd/MM/yyyy"
let strdateYesterday = dateFormatter.string(from: dateYesterday1)
if(startDate == strdateToday)
{
dateFormatter.dateFormat = "HH:mm"
let startDate = dateFormatter.string(from: date!)
print(startDate)
}
else if(startDate == strdateYesterday)
{
print("Yesterday")
}
else
{
print(startDate)
}
This question already has answers here:
Dateformatter to get Date From String
(4 answers)
Closed 4 years ago.
I have this structure:
struct message {
var id: String = "0"
var text: String = ""
var date: Date!
var status: String = ""
}
I have to load this structure from dbase, that it export in String format also date.
So I write this code to convert String to Date type:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.timeZone = NSTimeZone(abbreviation: "UTC") as TimeZone!
let dataDate = dateFormatter.date(from: elemMessage["date"] as! String)!
And I load it in structure:
message(id: elemMessage["id"] as! String, text: elemMessage["text"] as! String, date: dataDate as! Date, status: elemMessage["status"] as! String)
But I have this warning: "Cast from Date to unrelated type Date always fails"
So if I run app it will fails.
How Can I fix this, the date var in structure have to be Date type.
Thank you.
You can convert String Date into Date/NSDate like below code: -
Swift 3.2 & Swift 4.2
String to Date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy" //Your date format
dateFormatter.timeZone = TimeZone(abbreviation: "GMT+0:00") //Current time zone
//according to date format your date string
guard let date = dateFormatter.date(from: "01-01-2017") else {
fatalError()
}
print(date) //Convert String to Date
Date to String
dateFormatter.dateFormat = "MMM d, yyyy" //Your New Date format as per requirement change it own
let newDate = dateFormatter.string(from: date) //pass Date here
print(newDate) //New formatted Date string
Output: -
2017-01-11 00:07:00 +0000
Jan 11, 2017
Swift 4 ISO
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.timeZone = TimeZone.autoupdatingCurrent
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
func getDateFromString(dateStr: String) -> (date: Date?,conversion: Bool)
{
let calendar = Calendar(identifier: Calendar.Identifier.gregorian)
let dateComponentArray = dateStr.components(separatedBy: "/")
if dateComponentArray.count == 3 {
var components = DateComponents()
components.year = Int(dateComponentArray[2])
components.month = Int(dateComponentArray[1])
components.day = Int(dateComponentArray[0])
components.timeZone = TimeZone(abbreviation: "GMT+0:00")
guard let date = calendar.date(from: components) else {
return (nil , false)
}
return (date,true)
} else {
return (nil,false)
}
}
//Input: "23/02/2017"
//Output: (2017-02-23 18:30:00 +0000, true)
I have a UIDatePicker that is connected to a UILabel. I want the user to pick a birthday that is more than 18 years ago (age restriction). So I have this line to set the maximumDate value:
datePicker.maximumDate = NSCalendar.currentCalendar().dateByAddingUnit(.Year, value: -18, toDate: NSDate(), options: [])
This line however causes the picker to show a 1 day behind the selected date. for example if I choose September 27, 1956 on the picker the label shows September 26, 1956 I believe it has to do with NSDate() using a different timezone one that is behind my local timezone.
switch dequeueFrom[indexPath.row] {
case .Birthday:
if let pickedBday = pickedBday,
let bday = NSDate.dateFromISOString(pickedBday) {
(cell as! RegisterTextFieldCell).content(bday.longFormattedString())
}
// dateFromISOSString is declared in an extension.swift
class func dateFromComponents(components: NSDateComponents) -> NSDate? {
let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)
return calendar?.dateFromComponents(components)
}
class func dateFromString(string: String) -> NSDate? {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss-SSS"
if let stringDate = dateFormatter.dateFromString(string) {
return stringDate
} else {
return nil
}
}
func ISOStringFromDate() -> String {
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"
return dateFormatter.stringFromDate(self).stringByAppendingString("Z")
}
class func dateFromISOString(string: String) -> NSDate? {
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
if let stringDate = dateFormatter.dateFromString(string) {
return stringDate
} else {
return nil
}
}
Any help with how I can make NSDate() be my local timezone so this one day behind issue can go away? Any help is greatly appreciated :)
The problem is in your method ISOStringFromDate because you are getting the local time and manually adding the Z (Z means UTC) to the string. Try like this when creating your iso8601:
extension NSDate {
var iso8601: String {
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
dateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
return dateFormatter.stringFromDate(self)
}
}
and your code should be:
pickedDate.iso8601 // to get your date iso8601 string