Skip to content

Instantly share code, notes, and snippets.

@sssbohdan
Last active August 18, 2017 14:02
Show Gist options
  • Save sssbohdan/9211e4314da02885c9992baffc9e6ac0 to your computer and use it in GitHub Desktop.
Save sssbohdan/9211e4314da02885c9992baffc9e6ac0 to your computer and use it in GitHub Desktop.
DateFormatterHelper
//
// DateFormatterHelper.swift
// Rolique
//
// Created by Bohdan Savych on 8/18/17.
// Copyright © 2017 Rolique. All rights reserved.
//
import UIKit
extension Date {
var startOfWeek: Date {
return Calendar.current.date(from: Calendar.current.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self))!
}
var startOfDay: Date {
return Calendar.current.date(from: Calendar.current.dateComponents([.year, .month, .day], from: self))!
}
}
extension TimeInterval {
static var minute: TimeInterval {
return 60
}
static var hour: TimeInterval {
return minute * 60
}
static var day: TimeInterval {
return hour * 24
}
static var week: TimeInterval {
return day * 7
}
static var notLeapYear: TimeInterval {
return day * 365
}
static var leapYear: TimeInterval {
return day * 366
}
}
enum DateFormatterType: String {
case `default` = "yyyy-MM-dd HH:mm:ss ZZZZZ",
weekDay = "EEEE",
hourMinute = "HH:mm",
ddMMyyy = "dd/MM/yyyy"
}
final class DateFormatterHelper {
fileprivate static let formatter = DateFormatter()
static func convertToDate(from string: String, with type: DateFormatterType = .default) -> Date? {
objc_sync_enter(self)
defer { objc_sync_exit(self) }
formatter.dateFormat = type.r
return formatter.date(from: string)
}
static func convertToString(from date: Date, with type: DateFormatterType = .default) -> String {
objc_sync_enter(self)
defer { objc_sync_exit(self) }
formatter.dateFormat = type.r
return formatter.string(from: date)
}
// MARK: - Custom
static func messageString(from string: String, with type: DateFormatterType) -> String? {
guard let date = convertToDate(from: string, with: type) else { return nil }
return messageString(from: date)
}
static func messageString(from date: Date) -> String {
let currentDate = Date()
let startOfCurrentWeek = currentDate.startOfWeek
let startOfCurrentDay = currentDate.startOfDay
let startOfCurrentDayDiff = date.timeIntervalSince(startOfCurrentDay)
if startOfCurrentDayDiff > 0 {
return convertToString(from: date, with: .hourMinute)
}
let startOfCurrentWeekDiff = date.timeIntervalSince(startOfCurrentWeek)
if startOfCurrentWeekDiff > 0 {
return convertToString(from: date, with: .weekDay)
}
return convertToString(from: date, with: .ddMMyyy)
}
}
@sssbohdan
Copy link
Author

da eta joska

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment