I want to get the only date in iOS and not time
my code is
extension Date{
var DateInDate: Date{
let formatter = DateFormatter()
formatter.setLocalizedDateFormatFromTemplate("yyyy-MM-dd")
formatter.locale = Locale(identifier: "en_IN")
let dateInString = formatter.string(from: self)
return formatter.date(from: dateInString)!
}
}
if I am doing by the above format I am getting the answer as "Apr 3, 2019 at 12: 00 AM"
my other code is
extension Date{
var DateInDate: String{
let formatter = DateFormatter()
formatter.dateStyle = .short
formatter.timeStyle = .none
formatter.setLocalizedDateFormatFromTemplate("yyyy-MM-dd")
formatter.locale = Locale(identifier: "en_IN")
let dateInString = formatter.string(from: self)
}
}
but in this way, I am getting in string format and not a Date format
I want the answer in date format
As mentioned in the comments a Date instance without the time portion is impossible.
In terms of Date a timeless date is midnight, the start of the day.
There is an convenience API in Calendar:
let startOfDay = Calendar.current.startOfDay(for: Date())
You should use DateComponents instead. Date would always have the time.
Try this:
let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.timeStyle = DateFormatter.Style.none
dateFormatter.dateStyle = DateFormatter.Style.short
dateFormatter.string(from: date)
Related
Context
I have a custom Stringify Method on Date formatting a given Date into a String.
The result looks like this:
October 17th, 2022 at 1:27pm
However, when the Date is Today, Yesterday or Tomorrow, I would like to replace the actual Date with this specific String description. The result should look like this:
Today at 1:27pm
Code
extension Date {
func stringify() -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .long
dateFormatter.timeStyle = .short
return dateFormatter.string(from: self)
}
}
Question
How can I achieve this behaviour, since DateFormatter is not supporting it?
As suggested in the comments, you can use DateFormatter for this, the trick is to turn on the doesRelativeDateFormatting flag.
let today = Date()
let yesterday = Calendar.current.date(byAdding: .day, value: -1, to: today)!
let tomorrow = Calendar.current.date(byAdding: .day, value: 1, to: today)!
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .long
dateFormatter.timeStyle = .short
dateFormatter.doesRelativeDateFormatting = true
let todayString = dateFormatter.string(from: today)
print(todayString) // Today at 20:44
let yesterdayString = dateFormatter.string(from: yesterday)
print(yesterdayString) // Yesterday at 20:44
let tomorrowString = dateFormatter.string(from: tomorrow)
print(tomorrowString) // Tomorrow at 20:44
I am getting some date string from server, like "2021-06-25"
If it is today date or yesterday date, I have to show like Today or Yesterday.
Else I have to show 25 June 2021
For Today and Yesterday date its working fine.
But, If its other day, it is showing 25 Jun 2021
How to show 21 June 2021
static func getDay(_ nowDay: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let journalDate = dateFormatter.date(from: nowDay)
if let convertedDate = journalDate {
let relativeDateFormatter = DateFormatter()
relativeDateFormatter.timeStyle = .none
relativeDateFormatter.dateStyle = .medium
relativeDateFormatter.locale = Locale(identifier: "en_GB")
relativeDateFormatter.doesRelativeDateFormatting = true
let inputFormatter = DateFormatter()
inputFormatter.dateFormat = "yyyy-MM-dd"
return relativeDateFormatter.string(from: convertedDate)
}
return ""
}
Any suggestions?
If you want the full name of the month, use .long rather than .medium as the date style:
relativeDateFormatter.dateStyle = .long
Also note that you can use a ISO8601DateFormatter to parse nowDay, since it is in ISO-8601 format:
let dateFormatter = ISO8601DateFormatter()
dateFormatter.formatOptions = [.withFullDate]
let journalDate = dateFormatter.date(from: nowDay)
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
let dateFormatter = DateFormatter()
let dateFormatter2 = DateFormatter()
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let date = dateFormatter.date(from: event!)
dateFormatter2.timeZone = TimeZone.current
let dateString = dateFormatter2.string(from: date!)
let finalDate = dateFormatter2.date(from: dateString)
return finalDate!
I have sports events that give me string dates in UTC which I am trying to convert into local time. This code is similar to the dozens of examples given in this site when asked this question, yet it doesn't work.
This is the iso8601 formatter :
static let iso8601: DateFormatter = {
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: .iso8601)
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
return formatter
}()
This turns your string into a Date.
You will need to add the time difference, most likely through TimeZone.autoupdatingCurrent
This question already has answers here:
Convert NSDate to NSString
(19 answers)
Closed 5 years ago.
I am trying to convert a NSDate to a String and then Change Format. But when I pass NSDate to String it is producing whitespace.
let formatter = DateFormatter()
let myString = (String(describing: date))
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let yourDate: Date? = formatter.date(from: myString)
formatter.dateFormat = "dd-MMM-yyyy"
print(yourDate)
you get the detail information from Apple Dateformatter Document.If you want to set the dateformat for your dateString, see this link , the detail dateformat you can get here
for e.g , do like
let formatter = DateFormatter()
// initially set the format based on your datepicker date / server String
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let myString = formatter.string(from: Date()) // string purpose I add here
// convert your string to date
let yourDate = formatter.date(from: myString)
//then again set the date format whhich type of output you need
formatter.dateFormat = "dd-MMM-yyyy"
// again convert your date to string
let myStringDate = formatter.string(from: yourDate!)
print(myStringDate)
you get the output as
I always use this code while converting Date to String . (Swift 3)
extension Date
{
func toString( dateFormat format : String ) -> String
{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
return dateFormatter.string(from: self)
}
}
and call like this . .
let today = Date()
today.toString(dateFormat: "dd-MM")
DateFormatter has some factory date styles for those too lazy to tinker with formatting strings. If you don't need a custom style, here's another option:
extension Date {
func asString(style: DateFormatter.Style) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = style
return dateFormatter.string(from: self)
}
}
This gives you the following styles:
short, medium, long, full
Example usage:
let myDate = Date()
myDate.asString(style: .full) // Wednesday, January 10, 2018
myDate.asString(style: .long) // January 10, 2018
myDate.asString(style: .medium) // Jan 10, 2018
myDate.asString(style: .short) // 1/10/18
Your updated code.update it.
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let myString = formatter.string(from: date as Date)
let yourDate: Date? = formatter.date(from: myString)
formatter.dateFormat = "dd-MMM-yyyy"
print(yourDate!)
Something to keep in mind when creating formatters is to try to reuse the same instance if you can, as formatters are fairly computationally expensive to create. The following is a pattern I frequently use for apps where I can share the same formatter app-wide, adapted from NSHipster.
extension DateFormatter {
static var sharedDateFormatter: DateFormatter = {
let dateFormatter = DateFormatter()
// Add your formatter configuration here
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
return dateFormatter
}()
}
Usage:
let dateString = DateFormatter.sharedDateFormatter.string(from: Date())
After allocating DateFormatter you need to give the formatted string
then you can convert as string like this way
var date = Date()
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let myString = formatter.string(from: date)
let yourDate: Date? = formatter.date(from: myString)
formatter.dateFormat = "dd-MMM-yyyy"
let updatedString = formatter.string(from: yourDate!)
print(updatedString)
OutPut
01-Mar-2017
You can use this extension:
extension Date {
func toString(withFormat format: String) -> String {
let formatter = DateFormatter()
formatter.dateFormat = format
let myString = formatter.string(from: self)
let yourDate = formatter.date(from: myString)
formatter.dateFormat = format
return formatter.string(from: yourDate!)
}
}
And use it in your view controller like this (replace <"yyyy"> with your format):
yourString = yourDate.toString(withFormat: "yyyy")