[swift] 파일 날짜 및 시간 정보 조회하기
파일의 날짜 및 시간 정보를 조회하는 방법을 알아보겠습니다. Swift 언어를 사용하여 파일의 생성 날짜, 수정 날짜, 마지막 액세스 날짜와 같은 정보를 가져올 수 있습니다.
파일 경로 지정하기
먼저, 날짜 및 시간 정보를 조회하려는 파일의 경로를 지정해야 합니다. 다음과 같이 파일의 경로를 문자열로 지정할 수 있습니다.
let filePath = "/Users/username/Documents/example.txt"
파일 속성 조회하기
파일의 속성을 조회하기 위해 FileManager
클래스의 attributesOfItem
메서드를 사용합니다. 이 메서드는 파일의 속성을 딕셔너리 형태로 반환합니다.
do {
let fileAttributes = try FileManager.default.attributesOfItem(atPath: filePath)
// 파일의 속성을 출력하는 예시 코드
print(fileAttributes)
} catch {
print("파일의 속성을 가져오는 데 실패했습니다: \(error)")
}
속성 값 조회하기
attributesOfItem
메서드의 반환 값인 딕셔너리에서 원하는 속성 값을 가져올 수 있습니다. 대표적인 파일 속성은 다음과 같습니다.
FileCreationDate
: 파일의 생성 날짜FileModificationDate
: 파일의 수정 날짜FileAccessDate
: 파일의 마지막 액세스 날짜
do {
let fileAttributes = try FileManager.default.attributesOfItem(atPath: filePath)
if let creationDate = fileAttributes[.creationDate] as? Date {
print("파일의 생성 날짜: \(creationDate)")
}
if let modificationDate = fileAttributes[.modificationDate] as? Date {
print("파일의 수정 날짜: \(modificationDate)")
}
if let accessDate = fileAttributes[.accessDate] as? Date {
print("파일의 마지막 액세스 날짜: \(accessDate)")
}
} catch {
print("파일의 속성을 가져오는 데 실패했습니다: \(error)")
}
코드 예제
다음은 전체 코드 예제입니다.
import Foundation
let filePath = "/Users/username/Documents/example.txt"
do {
let fileAttributes = try FileManager.default.attributesOfItem(atPath: filePath)
if let creationDate = fileAttributes[.creationDate] as? Date {
print("파일의 생성 날짜: \(creationDate)")
}
if let modificationDate = fileAttributes[.modificationDate] as? Date {
print("파일의 수정 날짜: \(modificationDate)")
}
if let accessDate = fileAttributes[.accessDate] as? Date {
print("파일의 마지막 액세스 날짜: \(accessDate)")
}
} catch {
print("파일의 속성을 가져오는 데 실패했습니다: \(error)")
}