Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Refactor] #520 - DateFormatter() 인스턴스 메모리 최적화 #528

Open
wants to merge 13 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions SOPT-iOS/Projects/Core/Sources/Enum/DateFormatType.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
//
// DateFormatType.swift
// Core
//
// Created by 강윤서 on 3/27/25.
// Copyright © 2025 SOPT-iOS. All rights reserved.
//

import Foundation

public enum DateFormatType: String {
case iso = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
case isoWithoutMillis = "yyyy-MM-dd'T'HH:mm:ss"
case dateTimeDash = "yyyy-MM-dd HH:mm:ss"
case dateWithDot = "yyyy.MM.dd"
case dateWithDash = "yyyy-MM-dd"
case dateWithSlash = "yy/MM/dd"
case monthDayWeek = "M월 d일 EEEE"
case monthDayWeekTime = "M월 d일 EEEE H:mm"
case monthDayWeekFullTime = "M월 d일 EEEE HH:mm"
case monthDayWithDot = "MM.dd"
case monthDayWIthDash = "MM-dd"
case time = "HH:mm"
case networkLogger = "dd/MM/yyyy HH:mm:ss"
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,8 @@ public extension String {

/// 서버에서 들어온 Date String을 Date 타입으로 반환하는 메서드
func toDate() -> Date {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
dateFormatter.timeZone = TimeZone(identifier: "KST")
if let date = dateFormatter.date(from: self) {
DateFormatManager.shared.setFormat(.iso)
if let date = DateFormatManager.shared.stringToDate(self) {
return date
} else {
print("toDate() convert error")
Expand All @@ -38,8 +36,7 @@ public extension String {

/// 서버에서 들어온 Date String을 UI에 적용 가능한 String 타입으로 반환하는 메서드
func serverTimeToString(forUse: TimeStringCase) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yy/MM/dd"
DateFormatManager.shared.setFormat(.dateWithSlash)

let currentTime = Int(Date().timeIntervalSince1970)

Expand All @@ -61,7 +58,7 @@ public extension String {
return "방금"
}
case .forDefault:
return dateFormatter.string(from: self.toDate())
return DateFormatManager.shared.dateToString(self.toDate())
}
}

Expand Down
77 changes: 77 additions & 0 deletions SOPT-iOS/Projects/Core/Sources/Utils/DateFormatterManager.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
//
// DateFormatterManager.swift
// Core
//
// Created by 강윤서 on 3/27/25.
// Copyright © 2025 SOPT-iOS. All rights reserved.
//

import Foundation

public final class DateFormatManager {
public static let shared = DateFormatManager()

public init() {
formatter.locale = Locale(identifier: "ko_KR")
formatter.timeZone = TimeZone(identifier: "Asia/Seoul")
}

private var formatter = DateFormatter()
}

public extension DateFormatManager {
func setFormat(_ format: DateFormatType) {
formatter.dateFormat = format.rawValue
}

/// 문자열을 원하는 포맷의 Date타입으로 변환
func stringToDate(_ value: String) -> Date? {
return formatter.date(from: value)
}

/// date타입을 원하는 포맷의 문자열로 변환
func dateToString(_ date: Date) -> String {
return formatter.string(from: date)
}

/// 문자열 날짜를 원하는 포맷의 String타입으로 변환
/// 변경할 값이 비어있다면 오늘 날짜를 반환
func transformDateFormat(_ target: String? = nil, from before: DateFormatType? = nil, to after: DateFormatType) -> String {
guard let target, let before
else {
setFormat(after)
return dateToString(Date())
}

setFormat(before)
guard let date = stringToDate(target) else { return "00:00" }

setFormat(after)
return formatter.string(from: date)
}

/// 서버에서 내려주는 iSO 포맷 타입을 원하는 타입으로 변환
func serverTimeToString(_ target: String, from format: DateFormatType, to serverFormat: DateFormatType = .iso) -> String {
setFormat(serverFormat)
guard let date = stringToDate(target) else { return "" }

setFormat(format)
return dateToString(date)
}

/// 시작 날짜와 종료 날짜 입력 받아 원하는 포맷으로 변경 후 문자열로 반환
func formatTimeInterval(start: String, end: String) -> String {
setFormat(.monthDayWeekFullTime)

guard let startDate = stringToDate(start),
let endDate = stringToDate(end)
else { return "" }

let startString = dateToString(startDate)

setFormat(.time)
let endString = dateToString(endDate)

return "\(startString) ~ \(endString)"
}
}
40 changes: 0 additions & 40 deletions SOPT-iOS/Projects/Core/Sources/Utils/setDateFormat.swift

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,8 @@ extension TodayAttendance {

public func toDomain() -> TodayAttendanceModel {
return .init(status: self.status,
attendedAt: setDateFormat(
date: self.attendedAt,
from: "yyyy-MM-dd'T'HH:mm:ss",
to: "HH:mm"))
attendedAt: DateFormatManager.shared.transformDateFormat(self.attendedAt,
from: .dateTimeDash,
to: .time))
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -286,8 +286,7 @@ extension ShowAttendanceVC {
private func setScheduledData(_ model: AttendanceScheduleModel) {

if self.sceneType == .scheduledDay {
let date = viewModel.formatTimeInterval(startDate: model.startDate,
endDate: model.endDate)
let date = DateFormatManager.shared.formatTimeInterval(start: "3월 29일 토요일 03:15", end: "3월 29일 토요일 03:15")
headerScheduleView.setData(date: date,
place: model.location,
todaySchedule: model.name,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,9 +91,12 @@ extension ShowAttendanceViewModel {
if model.type != SessionType.noSession.rawValue {
self.sceneType = .scheduledDay

let convertedStartDate = self.convertDateString(model.startDate)
let convertedEndDate = self.convertDateString(model.endDate)

let convertedStartDate = DateFormatManager.shared.serverTimeToString(model.startDate,
from: .isoWithoutMillis,
to: .monthDayWeekTime)
let convertedEndDate = DateFormatManager.shared.serverTimeToString(model.endDate,
from: .isoWithoutMillis,
to: .monthDayWeekTime)
let newModel = AttendanceScheduleModel(type: model.type,
id: model.id,
location: model.location,
Expand Down Expand Up @@ -154,33 +157,4 @@ extension ShowAttendanceViewModel {
}
.store(in: self.cancelBag)
}

private func convertDateString(_ dateString: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
dateFormatter.locale = Locale(identifier: "ko_KR")
dateFormatter.timeZone = TimeZone(identifier: "Asia/Seoul")

guard let date = dateFormatter.date(from: dateString) else { return "" }

dateFormatter.dateFormat = "M월 d일 EEEE H:mm"
return dateFormatter.string(from: date)
}

func formatTimeInterval(startDate: String, endDate: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "M월 d일 EEEE HH:mm"
dateFormatter.locale = Locale(identifier: "ko_KR")
dateFormatter.timeZone = TimeZone(identifier: "Asia/Seoul")

guard let startDateObject = dateFormatter.date(from: startDate),
let endDateObject = dateFormatter.date(from: endDate) else { return "" }

let formattedStartDate = dateFormatter.string(from: startDateObject)

dateFormatter.dateFormat = "HH:mm"
let formattedEndDate = dateFormatter.string(from: endDateObject)

return "\(formattedStartDate) ~ \(formattedEndDate)"
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public final class DailySoptuneMainVC: UIViewController, DailySoptuneMainViewCon
private let dateLabel = UILabel().then {
$0.textColor = DSKitAsset.Colors.gray100.color
$0.font = DSKitFontFamily.Suit.medium.font(size: 16)
$0.text = setDateFormat(to: "M월 d일 EEEE")
$0.text = DateFormatManager.shared.transformDateFormat(to: .monthDayWeek)
}

private let recieveFortune = UILabel().then {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ extension DailySoptuneMainViewModel {
input.receiveTodayFortuneButtonTap
.withUnretained(self)
.sink { owner, _ in
owner.useCase.getDailySoptuneResult(date: setDateFormat(to: "yyyy-MM-dd"))
owner.useCase.getDailySoptuneResult(date: DateFormatManager.shared.transformDateFormat(to: .dateWithDash))
AmplitudeInstance.shared.track(eventType: .clickCheckTodaySoptune)
}.store(in: cancelBag)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ extension DailySoptuneResultContentView {

extension DailySoptuneResultContentView {
public func setData(model: DailySoptuneResultModel) {
self.dateLabel.text = setDateFormat(to: "MM월 d일 EEEE")
self.dateLabel.text = DateFormatManager.shared.transformDateFormat(to: .monthDayWeek)
self.contentLabel.text = "\(model.userName)님,\n\(model.title.setLineBreakAtMiddle())"
self.contentLabel.setLineSpacing(lineSpacing: 5)
self.contentLabel.textAlignment = .center
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -128,8 +128,7 @@ extension CalendarCardCVC {
extension CalendarCardCVC {
func configureCell(model: HomePresentationModel.RecentSchedule,
userType: UserType) {
// TODO: 서버 - 날짜 포맷 변경 후 반영
self.dateLabel.text = setDateFormat(date: model.date, to: "MM.dd")
self.dateLabel.text = DateFormatManager.shared.transformDateFormat(model.date, from: .monthDayWIthDash, to: .monthDayWithDot)
Copy link
Contributor

@meltsplit meltsplit Mar 29, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

서버에서 받아온 날짜 관련 String을
뷰계층에서 from -> to로 바꿔주는 것이군요 :)

서버와 약속한 Date format으로 Date를 변환하는 역할은 누구에게 책임이 있다고 생각하시나요?
저는 해당 책임은 데이터 모듈 혹은 네트워크 모듈이 지녀야 한다고 생각해요.
서버의 문자열 format이 바뀌었을 때 뷰계층 코드를 변경하는 것보단 네트워크쪽 코드를 변경하는 것이 자연스럽다고 느껴지기 때문이에요

Date값이 Data계층에서 Domain계층으로 넘어갈 때 String 값을 Date값으로 변경하고,
Presentation 계층에선 Date -> String으로 변환하는 방식은 어떨까요?

Domain에는 가장 순수한 Date 타입만 존재하면 좋을 것 같아요

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

다시 생각해보니 해당 PR은 메모리 성능 최적화가 중점적이라, PR에서 작업하지 않은 내용을 리뷰한 것 같네요 ㅎㅎ;
그래도 같이 고민해보면 좋을 것 같습니다 .. :)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

리뷰 감사합니다 !! 기존 코드 수정에만 집중하다 보니 각 레이어의 역할 분리에 대해 깊이 있게 고민하지 못했던 것 같아요.

석우님 말씀처럼 서버에서 받아온 날짜(String)값Data -> Domain 단계에서 Date 타입으로로 변환하면 UI 상황에 맞게 다양한 포맷으로 변경할 수 있어 더 유연한 구조가 될 것 같네요 ! 리뷰에 함께 반영하도록 하겠습니다👍👍

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

피드백 수용해주셔서 감사함다 :)

현 구조에선 toDomain()에서 String을 Date로 변환하는 것이 가장 편할 것 같네요.

이외에도 서버의 requestBody의 json을 Decodable 구조체로 디코딩할 때 JSONDecoder의 dateStrategyFormat값을 통해 처음부터 해당 밸류값을 Date 타입으로도 받아오는 방법도 있습니다~!

self.scheduleTitleLabel.text = model.title
if let tagType = CalenderCategoryTagType(rawValue: model.type) {
self.scheduleCategoryTagView.setData(title: tagType.text,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -163,11 +163,8 @@ extension MissionDateView {
.publisher(for: .valueChanged)
.map { $0.date }
.sink(receiveValue: { [weak self] value in
let dateFormatter = DateFormatter().then {
$0.dateFormat = "yyyy.MM.dd"
$0.locale = .current
}
let formattedDate = dateFormatter.string(from: value)
DateFormatManager.shared.setFormat(.dateWithDot)
let formattedDate = DateFormatManager.shared.dateToString(value)
self?.selectAndFormattedDate = formattedDate
self?.textField.text = formattedDate
}).store(in: self.cancelBag)
Expand Down Expand Up @@ -208,11 +205,8 @@ extension MissionDateView {
if let selectAndFormattedDate = self?.selectAndFormattedDate {
date = selectAndFormattedDate
} else {
let dateFormatter = DateFormatter().then {
$0.dateFormat = "yyyy.MM.dd"
$0.locale = .current
}
date = dateFormatter.string(from: Date())
DateFormatManager.shared.setFormat(.dateWithDot)
date = DateFormatManager.shared.dateToString(Date())
}
self?.textField.text = date
self?.textField.resignFirstResponder()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@
import Foundation
import Moya

import Core

/// Logs network activity (outgoing requests and incoming responses).
public final class NetworkLoggerPlugin: PluginType {
fileprivate let loggerId = "Moya_Logger"
fileprivate let dateFormatString = "dd/MM/yyyy HH:mm:ss"
fileprivate let dateFormatter = DateFormatter()
fileprivate let separator = ", "
fileprivate let terminator = "\n"
fileprivate let cURLTerminator = "\\\n"
Expand Down Expand Up @@ -67,9 +67,8 @@ public final class NetworkLoggerPlugin: PluginType {
private extension NetworkLoggerPlugin {

var date: String {
dateFormatter.dateFormat = dateFormatString
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
return dateFormatter.string(from: Date())
DateFormatManager.shared.setFormat(.networkLogger)
return DateFormatManager.shared.dateToString(Date())
}

func format(_ loggerId: String, date: String, identifier: String, message: String) -> String {
Expand Down