46

I have variable with data type Date, where I have stored date in this format

2018-12-24 18:00:00 UTC

How can I get from this day or month?

Max
  • 825
  • 2
  • 7
  • 7
  • [Date components](https://nshipster.com/datecomponents/), [date components](https://stackoverflow.com/questions/38248941/how-to-get-time-hour-minute-second-in-swift-3-using-nsdate), [date components](https://www.andrewcbancroft.com/2016/05/26/swift-cheat-sheet-for-dates-formatters-date-components/) – MadProgrammer Nov 17 '18 at 23:10
  • Search Swift `DateFormatter()` and possibly `ISO8601DateFormatter()`. If all you need is the date and month from that, you can drop everything after the day value and use the `ISO8601DateFormatter` with these format options `[.withFullDate, .withDashSeparatorInDate]` – trndjc Nov 17 '18 at 23:13
  • Nearly a duplicate: https://stackoverflow.com/questions/44040875/swift-how-to-get-string-values-of-days-months-and-year-from-a-date-picker – rmaddy Nov 17 '18 at 23:15
  • 3
    You said "I have variable with data type Date, where I have stored date in this format `2018-12-24 18:00:00 UTC`." That doesn't make sense. If the data type is Date it doesn't have a string format. A `Date` is a primitive type that identifies an instant in time. It doesn't have a format. – Duncan C Nov 17 '18 at 23:37
  • If you display a date with `print(Date())` you'll get output like `2018-11-17 23:38:02 +0000` (The `+0000` bit is the offset from UTC. An offset of 0000 from UTC means the date/time is expressed in the UTC time zone.) – Duncan C Nov 17 '18 at 23:39

8 Answers8

73

Details

  • Xcode Version 11.0 (11A420a), Swift 5

Links

How to convert string to Date

Solution

extension Date {
    func get(_ components: Calendar.Component..., calendar: Calendar = Calendar.current) -> DateComponents {
        return calendar.dateComponents(Set(components), from: self)
    }

    func get(_ component: Calendar.Component, calendar: Calendar = Calendar.current) -> Int {
        return calendar.component(component, from: self)
    }
}

Usage

let date = Date()

// MARK: Way 1

let components = date.get(.day, .month, .year)
if let day = components.day, let month = components.month, let year = components.year {
    print("day: \(day), month: \(month), year: \(year)")
}

// MARK: Way 2

print("day: \(date.get(.day)), month: \(date.get(.month)), year: \(date.get(.year))")
Vasily Bodnarchuk
  • 24,482
  • 9
  • 132
  • 127
38

Is that String or Date type?

if it is date you can do so:

let calendarDate = Calendar.current.dateComponents([.day, .year, .month], from: date)

that will give you the day, year and month

jmartinalonso
  • 2,324
  • 1
  • 19
  • 22
ironRoei
  • 2,049
  • 24
  • 45
18

If you saved "2018-12-24 18:00:00 UTC" as a String, you can try this:

let dateString = "2018-12-24 18:00:00 UTC"
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss 'UTC'"
guard let date = formatter.date(from: dateString) else {
    return
}

formatter.dateFormat = "yyyy"
let year = formatter.string(from: date)
formatter.dateFormat = "MM"
let month = formatter.string(from: date)
formatter.dateFormat = "dd"
let day = formatter.string(from: date)
print(year, month, day) // 2018 12 24

Best Wishes!

McKinley
  • 1,123
  • 1
  • 8
  • 18
GorCat
  • 181
  • 6
2

The date string is not ISO8601 compliant, nevertheless you can use ISO8601DateFormatter if you replace <space> + UTC with Z and use custom format options.

Create a Date from the string and get the DateComponents for day and month

let string = "2018-12-24 18:00:00 UTC"

let formatter = ISO8601DateFormatter()
let trimmedString = string.replacingOccurrences(of: "\\s?UTC", with: "Z", options: .regularExpression)
formatter.formatOptions = [.withFullDate, .withFullTime, .withSpaceBetweenDateAndTime]
if let date = formatter.date(from: trimmedString) {
    let components = Calendar.current.dateComponents([.day, .month], from: date)
    let day = components.day!
    let month = components.month!
    print(day, month)
}
vadian
  • 274,689
  • 30
  • 353
  • 361
1

If you have a date variable you can also use this solution for SwiftUi:

let date = Date()

Text(date, style: .time) // January 8, 2023
Text(date, style: .date) // 12:08 PM
Iskandir
  • 937
  • 1
  • 9
  • 21
0

This is how I did in swift 4. I have a Billing class with "billDate" a field that contains the date.

extension Billing:Identifiable{
 func month() -> String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "MMM"
    
    if let inputDate = billDate {
        let month = dateFormatter.string(from: inputDate)
        
        return month.uppercased()
    }
    return ""
}
Amit Baderia
  • 4,454
  • 3
  • 27
  • 19
0

Extention Date All Time RETURN String:

extension Date {
func dateDistance(_ startDate: Date = Date()) -> String {
    var remainingTime = ""
    let dateValue = Calendar.current.dateComponents([.year,.month,.weekOfMonth,.day,.hour,.minute,.second], from: startDate, to: self)
    
    remainingTime = String(format: "%2d Y - %2d M - %2d W - %2d D\n%02d:%02d:%02d",
                        dateValue.year ?? 0,
                        dateValue.month ?? 0,
                        dateValue.weekOfMonth ?? 0,
                        dateValue.day ?? 0,
                        dateValue.hour ?? 0,
                        dateValue.minute ?? 0,
                        dateValue.second ?? 0
              )
    
    return remainingTime
}
}
ZygD
  • 22,092
  • 39
  • 79
  • 102
0
extension Date {
   func getRemainingDayMonthYear (_ startDate: Date = Date()) -> String 
    {
        var remainingTime = ""
        let dateValue = Calendar.current.dateComponents([.year,.month,.weekOfMonth,.day,.hour,.minute,.second], from: startDate, to: self)
        
        if dateValue.year ?? 0 > 0  {
            remainingTime = dateValue.year ?? 0 > 1 ? String(format: "%2d Years",dateValue.year ?? 0) : String(format: "%2d Year",dateValue.year ?? 0)
        } else if dateValue.month ?? 0 > 0 {
            remainingTime = dateValue.month ?? 0 > 1 ? String(format: "%2d Months",dateValue.month ?? 0) : String(format: "%2d Month",dateValue.month ?? 0)
        } else {enter code here
            remainingTime = dateValue.day ?? 0 > 1 ? String(format: "%2d Days",dateValue.day ?? 0) : String(format: "%2d Day",dateValue.day ?? 0)
        }    
        return remainingTime
    }
}
vimuth
  • 5,064
  • 33
  • 79
  • 116