This function gets the tapped date when tapping the calendar date.
What I want to realize is, for example, when I tap 2018/11/1, I want to get the string "2018/11/01", but I do not know how to do it. Could you tell me?
func getDay(_ date:Date) -> (Int,Int,Int,String){
let tmpCalendar = Calendar(identifier: .gregorian)
let Component = tmpCalendar.component(.weekday, from: date)
let weekName = Component - 1
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "ja")
let year = tmpCalendar.component(.year, from: date)
let month = tmpCalendar.component(.month, from: date)
let day = tmpCalendar.component(.day, from: date)
return (year,month,day,formatter.shortWeekdaySymbols[weekName])
}
func calendar(_ calendar: FSCalendar, didSelect date: Date, at monthPosition: FSCalendarMonthPosition){
let selectDay = getDay(date)
let scheduleForDate = "\(String(selectDay.0))/\(String(selectDay.1))/\(String(selectDay.2))"
print(scheduleForDate)
getStartScheduleDate(date: scheduleForDate)
tableView.reloadData()
}
By the way, the library I am using is FSCalendar.
Use a DateFormatter set to the format you want.
let formatter = DateFormatter()
formatter.dateFormat = "yyyy/MM/dd"
let result = formatter.string(from: someDate)
But it's not a good idea to use such a format to show dates to a user. It's ambiguous. Is that November 1st or January 11th?
It's better to use a date style so the date is shown to the user in their own expected format given their locale.
let formatter = DateFormatter()
formatter.dateStyle = .short
let result = formatter.string(from: someDate)
Or at least localize the specific format:
let formatter = DateFormatter()
formatter.setLocalizedDateFormatFromTemplate("yyyyMMdd")
let result = formatter.string(from: someDate)
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 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)
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 can obtain the individual date components as:
let dateString = String(dataModel.dateCompletedDay) + String(dataModel.dateCompletedMonth) + String(dataModel.dateCompletedYear)
print(dateString)
//2532016
Now how can i to convert it to DD/MM/YYYY format?
I suggest to use Calendar, DateComponents and DateFormatter (Swift 3)
let components = DateComponents(year:dataModel.dateCompletedYear, month: dataModel.dateCompletedMonth, day: dataModel.dateCompletedDay)
let calendar = Calendar(identifier: .gregorian)!
let date = calendar.date(from: components)!
let formatter = DateFormatter()
formatter.dateFormat = "dd/MM/yyyy"
let dateString = formatter.string(from: date)
Additionally this is a simple solution which is supposed to work also in Swift 2
let dateString = String(format: "%02ld/%02ld/%ld", dataModel.dateCompletedDay, dataModel.dateCompletedMonth, dataModel.dateCompletedYear)
I want this date "2016-10-18 22:06:20 +0000" to "18-10-2016", is this possible? I managed to get the date as follows:
var formatter = DateFormatter()
formatter.dateFormat = "yyy-MM-dd'HH:mm:ss.SSSZ"
let stringDate = formatter.string(from: currentDate)
The above gives me "10/18/16", but how can I get "18-10-2016"?
Solution in Swift 3
extension Foundation.Date {
func dashedStringFromDate() -> String {
let dateFormatter = DateFormatter()
let date = self
dateFormatter.dateFormat = "dd-MM-yyyy"
return dateFormatter.string(from: date)
}
}
Example
let date = Foundation.Date()
let formatedDate = date.dashedStringFromDate()
Little about what you put in your question makes a lot of sense. You don't have a date as 2016-10-18 22:06:20 +0000. The code you posted converts a current Date into a string. But you claim you want that string to be in the format 18-10-2016 but your code uses a completely different format.
Why not just do:
var formatter = DateFormatter()
formatter.dateFormat = "dd-MM-yyyy"
let stringDate = formatter.string(from: currentDate)
This will convert the currentDate to a string in the format you mention in your question.
If you really have a string in the format of 2016-10-18 22:06:20 +0000 and you want to convert it to 18-10-2016, then you want two date formatters.
The first convert that original string to a date:
let string = "2016-10-18 22:06:20 +0000"
let formatter1 = DateFormatter()
formatter1.locale = Locale(identifier: "en_US_POSIX") // if this string was from web service or a database, you should set the locale
formatter1.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
guard let date = formatter1.date(from: string) else {
fatalError("Couldn't parse original date string")
}
If you then want to build a new string in the format of 18-10-2016, then you'd use a second formatter:
let formatter2 = DateFormatter()
formatter2.dateFormat = "dd-MM-yyyy"
let result = formatter2.string(from: date)