Date के Basics
एक Date समय में एक precise point है, और Swift आपको उन moments को compare, calculate, और print करने के tools देता है।
Syntax
import Foundation
let now = Date()
let later = now.addingTimeInterval(seconds)
let isEarlier = now < later
let seconds = later.timeIntervalSince(now)
Creating and Comparing Dates
Date() current moment देता है, और dates को यह देखने के लिए numbers की तरह compare किया जा सकता है कि कौन सा पहले आया।
उदाहरण: Creating and Comparing Dates
// Import the `Foundation` module
import Foundation
// Declare a constant `now`, set to `Date()`
let now = Date()
// Declare a constant `later`, set to `now.addingTimeInterval(60)`
let later = now.addingTimeInterval(60)
// Print `now < later` to the console
print(now < later)
Login to try C/C++/Java/PHP code in the editor
Measuring the Interval Between Dates
.timeIntervalSince(_:) दो dates को अलग करने वाले seconds की संख्या compute करता है, durations measure करने के लिए उपयोगी।
उदाहरण: Measuring the Interval Between Dates
// Import the `Foundation` module
import Foundation
// Declare a constant `start`, set to `Date()`
let start = Date()
// Declare a constant `end`, set to `start.addingTimeInterval(3600)`
let end = start.addingTimeInterval(3600)
// Declare a constant `interval`, set to `end.timeIntervalSince(start)`
let interval = end.timeIntervalSince(start)
// Print "Interval in seconds: \(interval)" to the console
print("Interval in seconds: \(interval)")
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
आम गलतियां
- यह भूल जाना कि Foundation से
Dateको उपयोग होने से पहले file के top परimport Foundationचाहिए। - एक raw
Dateको सीधे print करना और locale-friendly formatting की उम्मीद करना; readable output के लिए एकDateFormatterउपयोग करें। - यह मान लेना कि
Date()एक fixed value return करता है; हर call current moment capture करती है, इसलिए results calls और machines में अलग होते हैं।
चैप्टर सारांश
- Foundation से
Date()समय में current point capture करता है। - दो dates सीधे
<,>, और==से compare किए जा सकते हैं। .timeIntervalSince(_:)दो dates के बीच seconds की संख्या compute करता है।DateFormatter(या newerDate.FormatStyle) एकDateको human-readable text में convert करता है।
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: