Classe Java Instant

La classe Instant est une classe importante de l'API date-heure (paquetage java.time) introduite dans Java 8. Elle représente un point instantané sur la ligne temporelle. Cette classe est principalement utilisée pour enregistrer des horodatages avec une précision à la nanoseconde.

La classe Instant possède les principales caractéristiques suivantes :

  • Représente le temps à partir de 1970-01-01T00:00:00Z (l'époque Unix)
  • Ne contient pas d'informations de fuseau horaire
  • Est immuable et thread-safe
  • Précis à la nanoseconde (alors que la classe Date traditionnelle n'est précise qu'à la milliseconde)

Création d'un objet Instant

Obtenir le moment actuel

Exemple

Instant now = Instant.now();  // Obtenir le moment actuel

Créer à partir du temps d'époque

Exemple

Instant instant1 = Instant.ofEpochSecond(3);  // 1970-01-01T00:00:03Z
Instant instant2 = Instant.ofEpochSecond(3, 0);  // Identique à ci-dessus
Instant instant3 = Instant.ofEpochSecond(2, 1_000_000_000);  // 1 nanoseconde après 3 secondes
Instant instant4 = Instant.ofEpochSecond(4, -1_000_000_000);  // 1 nanoseconde avant 3 secondes

Créer à partir de millisecondes

Exemple

Instant instant = Instant.ofEpochMilli(1000);  // 1970-01-01T00:00:01Z

Méthodes courantes de la classe Instant

Obtenir des informations temporelles

Exemple

Instant instant = Instant.now();

long seconds = instant.getEpochSecond();  // Obtenir le nombre de secondes depuis 1970-01-01
int nanos = instant.getNano();  // Obtenir la partie en nanosecondes

Comparaison temporelle

Exemple

Instant instant1 = Instant.now();
Instant instant2 = instant1.plusSeconds(10);

boolean isBefore = instant1.isBefore(instant2);  // true
boolean isAfter = instant1.isAfter(instant2);  // false

Arithmétique temporelle

Exemple

Instant instant = Instant.now();

// Ajouter 10 secondes
Instant later = instant.plusSeconds(10);

// Soustraire 5 minutes
Instant earlier = instant.minus(Duration.ofMinutes(5));

// Ajouter 2 jours, 4 heures et 30 minutes
Instant future = instant.plus(2, ChronoUnit.DAYS)
                       .plus(4, ChronoUnit.HOURS)
                       .plus(30, ChronoUnit.MINUTES);

Conversion entre Instant et d'autres classes de date-heure

Instant et LocalDateTime

Exemple

Instant instant = Instant.now();

// Convertir Instant en LocalDateTime
LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());

// Convertir LocalDateTime en Instant
Instant fromLdt = ldt.toInstant(ZoneOffset.UTC);

Instant et ZonedDateTime

Exemple

Instant instant = Instant.now();

// Convertir Instant en ZonedDateTime
ZonedDateTime zdt = instant.atZone(ZoneId.of("Asia/Shanghai"));

// Convertir ZonedDateTime en Instant
Instant fromZdt = zdt.toInstant();

Instant et Date

Exemple

// Convertir Instant en Date
Date date = Date.from(instant);

// Convertir Date en Instant
Instant fromDate = date.toInstant();

Applications pratiques de la classe Instant

Enregistrement des horodatages d'événements

Exemple

public class Event {
    private String name;
    private Instant timestamp;
   
    public Event(String name) {
        this.name = name;
        this.timestamp = Instant.now();
    }
   
    // accesseurs...
}

Calcul des intervalles de temps

Exemple

Instant start = Instant.now();
// Effectuer quelques opérations...
Instant end = Instant.now();

Duration duration = Duration.between(start, end);
System.out.println(" milliseconds" + duration.toMillis() + " milliseconds");

Tâches planifiées

Exemple

Instant now = Instant.now();
Instant nextRun = now.plus(1, ChronoUnit.HOURS);

while (Instant.now().isBefore(nextRun)) {
    // Attendre jusqu'à l'heure spécifiée
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

// Exécuter la tâche planifiée
System.out.println("Heure d'exécution de la tâche planifiée : " + Instant.now());

Exemple complet

Exemple

import java.time.Instant;
import java.time.Duration;
import java.time.temporal.ChronoUnit;

public class InstantExample {
    public static void main(String[] args) {
        // 1. Obtenir l'Instant pour le moment actuel
        Instant now = Instant.now();
        System.out.println("Moment actuel : " + now);
       
        // 2. Analyser un Instant à partir d'une chaîne
        Instant parsedInstant = Instant.parse("2023-05-15T10:15:30.00Z");
        System.out.println("Instant analysé : " + parsedInstant);
       
        // 3. Créer un Instant pour un moment précis
        Instant epochInstant = Instant.ofEpochSecond(0);
        System.out.println("Temps epoch (1970-01-01T00:00:00Z) : " + epochInstant);
       
        Instant specificInstant = Instant.ofEpochSecond(1684131330);
        System.out.println("Horodatage spécifique : " + specificInstant);
       
        // 4. Arithmétique temporelle
        Instant later = now.plusSeconds(60); // Ajouter 60 secondes
        System.out.println("Après 60 secondes : " + later);
       
        Instant earlier = now.minus(2, ChronoUnit.HOURS); // Soustraire 2 heures
        System.out.println("Il y a 2 heures : " + earlier);
       
        // 5. Calculer l'intervalle de temps
        Duration duration = Duration.between(earlier, later);
        System.out.println("Intervalle de temps : " + duration.toMinutes() + " minutes");
       
        // 6. Comparer les instants
        System.out.println("Est-ce que earlier est avant later : " + earlier.isBefore(later));
        System.out.println("Est-ce que later est après earlier : " + later.isAfter(earlier));
       
        // 7. Obtenir les horodatages
        System.out.println("Secondes depuis l'époque : " + now.getEpochSecond());
        System.out.println("Partie en nanosecondes : " + now.getNano());
    }
}

Le résultat de sortie est similaire à ce qui suit :

当前时刻: 2025-05-01T03:19:09.345806Z
解析的 Instant: 2023-05-15T10:15:30Z
纪元时间 (1970-01-01T00:00:00Z): 1970-01-01T00:00:00Z
特定时间戳: 2023-05-15T06:15:30Z
60秒后: 2025-05-01T03:20:09.345806Z
2小时前: 2025-05-01T01:19:09.345806Z
时间间隔: 121 分钟
earlier 是否在 later 之前: true
later 是否在 earlier 之后: true
从纪元开始的秒数: 1746069549
纳秒部分: 345806000

Remarques sur la classe Instant

  1. Problèmes de fuseau horaire: Instant ne contient pas d'informations de fuseau horaire ; il représente toujours l'heure UTC. Si vous devez afficher l'heure dans un fuseau horaire spécifique, vous devez la convertir en ZonedDateTime.

  2. Problèmes de précision: La précision de Instant dépend du système d'exploitation et du matériel ; la plupart des systèmes ne peuvent fournir qu'une précision à l'échelle de la milliseconde.

  3. Immutabilité: La classe Instant est immuable ; toutes les opérations de modification renvoient un nouvel objet Instant.

  4. Opérations de comparaison: Lorsque vous comparez deux objets Instant, vous devez utiliser les méthodes isBefore() et isAfter() au lieu de comparer directement les horodatages.

  5. Sérialisation: La classe Instant implémente l'interface Serializable et peut être sérialisée et désérialisée en toute sécurité.

Autres extensions