Search code examples
iosswiftnsdatensdateformatter

How to turn a dateFormatter value such as Jul 07, 2019 into Jul 7, 2019 from timestamp?


I made a convertDate class for functionality to convert my timestamps which are Date().sinceReferenceDate (i.e. since January 1, 2001 12:00am). I have one problem: when the date of the timestamp is over 3 weeks ago, I use the date format (Month, Day, Year (if earlier than current year)), but the issue is that if the day is not over 10, then the day looks like this: 01,02,03 (Jul 01, Jul 02), etc. while I need it to be 1,2,3 (Jul 1, Jul 2). I have been unable to find a solution, here's my code:

let nowTime = Date.timeIntervalSinceReferenceDate
let finalTime = nowTime - mediaTimestamp //how long ago in seconds...

//For timestamp coverting below
print(mediaTimestamp, "<-- datfasfePass")
let timeToModify = Date(timeIntervalSinceReferenceDate: mediaTimestamp)
let formatter = DateFormatter()
formatter.dateFormat = "MMM dd, yyyy"

//Below is for excluding the 2019 if the current year is 2019
let formatterForYear = DateFormatter()
formatterForYear.dateFormat = "yyyy"
let currentYear = "2019" //this is hardcoded right now
let finalYearDetermine = formatterForYear.string(from: timeToModify)
let currentFormatterYear = finalYearDetermine
print(currentFormatterYear, "<-- currentFormatterYear")

var finalDate = formatter.string(from: timeToModify)

if currentYear == finalYearDetermine {
    //then its currently 2019 whitch means we exclude the 2019
    formatter.dateFormat = "MMM dd"
    finalDate = formatter.string(from: timeToModify)
} else {
    //do nothing to dateformtter
}

finalDateString = "\(finalDate)"

Solution

  • To directly answer your question, you just need to use a single 'd' for the date e.g.:

    formatter.dateFormat = "MMM d"
    

    However you should consider using the device locale to display your dates. DateFormatter does this automatically if you do not set a format or override the locale property:

    let formatter = DateFormatter()
    formatter.dateStyle = .medium
    

    EDIT: To drop the year component while still supporting the device locale you can use:

    let formatter = DateFormatter()
    formatter.setLocalizedDateFormatFromTemplate("MMMd")
    

    This will output "Jul 6" for a en_US locale but "6 Jul" for en_AU locale (for example).