← Back to Swift Course | Chapter 14: Standard Library & Best Practices | Lesson 2 of 7

Date के Basics

एक Date समय में एक precise point है, और Swift आपको उन moments को compare, calculate, और print करने के tools देता है।
Syntax
swift
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

markup
// 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)

Measuring the Interval Between Dates

.timeIntervalSince(_:) दो dates को अलग करने वाले seconds की संख्या compute करता है, durations measure करने के लिए उपयोगी।

उदाहरण: Measuring the Interval Between Dates

markup
// 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)")
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. #}
आम गलतियां
  1. यह भूल जाना कि Foundation से Date को उपयोग होने से पहले file के top पर import Foundation चाहिए।
  2. एक raw Date को सीधे print करना और locale-friendly formatting की उम्मीद करना; readable output के लिए एक DateFormatter उपयोग करें।
  3. यह मान लेना कि Date() एक fixed value return करता है; हर call current moment capture करती है, इसलिए results calls और machines में अलग होते हैं।
चैप्टर सारांश
  • Foundation से Date() समय में current point capture करता है।
  • दो dates सीधे <, >, और == से compare किए जा सकते हैं।
  • .timeIntervalSince(_:) दो dates के बीच seconds की संख्या compute करता है।
  • DateFormatter (या newer Date.FormatStyle) एक Date को human-readable text में convert करता है।
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.