Last active
March 12, 2020 12:03
-
-
Save egzonpllana/78ec999cb6a4a1b62e510a45f03be478 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Timestamp+ReadableDate.swift | |
// EReminder | |
// | |
// Created by Egzon Pllana on 3/12/20. | |
// Copyright © 2020 Native Coders. All rights reserved. | |
// | |
import Foundation | |
// NOTE: Readable date system is implemented from this github gist and improved later from me | |
// https://gist.github.com/akultomar17/8210340c4808e3d7a2bcb1c0fb4523b8#file-epochtoreadabledates-swift | |
extension Date { | |
var readableDate: String { | |
let date = Date(timeIntervalSince1970: self.timeIntervalSince1970) | |
let dateFormatter = DateFormatter() | |
var time: String | |
if Calendar.current.isDateInTomorrow(date) { | |
dateFormatter.dateFormat = "h:mm a" | |
time = dateFormatter.string(from: date) | |
return "Tomorrow at \(time)" | |
} else if Calendar.current.isDateInYesterday(date) { | |
dateFormatter.dateFormat = "h:mm a" | |
time = dateFormatter.string(from: date) | |
return "Yesterday at \(time)" | |
} else if Calendar.current.isDateInToday(date) { | |
dateFormatter.dateFormat = "h:mm a" | |
time = dateFormatter.string(from: date) | |
return "Today at \(time)" | |
} else { | |
// show year if date is in the next years | |
dateFormatter.dateFormat = "YYYY" | |
let dateToString = dateFormatter.string(from: date) | |
if let yearToInt = Int(dateToString), self.currentYear == yearToInt { | |
dateFormatter.dateFormat = "dd MMM, hh:mm a" | |
} else { | |
dateFormatter.dateFormat = "dd MMM yyyy, hh:mm a" | |
} | |
time = dateFormatter.string(from: date) | |
return time | |
} | |
} | |
var currentYear: Int { | |
let date = Date(timeIntervalSince1970: self.timeIntervalSince1970) | |
let dateFormatter = DateFormatter() | |
dateFormatter.dateFormat = "YYYY" | |
let dateToString = dateFormatter.string(from: date) | |
if let dateToInt = Int(dateToString) { | |
return dateToInt | |
} else { | |
return 0000 | |
} | |
} | |
private func dateFallsInCurrentWeek(date: Date) -> Bool { | |
let currentWeek = Calendar.current.component(Calendar.Component.weekOfYear, from: Date()) | |
let datesWeek = Calendar.current.component(Calendar.Component.weekOfYear, from: date) | |
return (currentWeek == datesWeek) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment