Introduction
Une chaîne de caractères représentant une date peut être convertie en horodatage (timestamp) en utilisant les classes SimpleDateFormat, Timestamp et Date de Java. Ce laboratoire (lab) couvrira deux méthodes pour convertir une chaîne de caractères représentant une date en horodatage.
Convertir une chaîne de caractères en date en utilisant la méthode parse()
import java.text.SimpleDateFormat;
import java.sql.Timestamp;
import java.util.Date;
public class StringToTimestamp {
public static void main(String[] args) throws Exception {
// date in string format
String stringDate = "2021-01-07 02:02:16.172";
try {
// creating date format
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
// parsing string to date using parse() method
Date parsedDate = dateFormat.parse(stringDate);
// finally creating a timestamp
Timestamp timestamp = new java.sql.Timestamp(parsedDate.getTime());
System.out.println(timestamp);
} catch(Exception e) {
System.out.println(e);
}
}
}
Pour exécuter ce programme, ouvrez le terminal et accédez au répertoire ~/project/.
Convertir une date sous forme de chaîne de caractères en horodatage (timestamp) en utilisant la méthode valueOf()
Ceci est une autre méthode pour convertir une chaîne de caractères représentant une date en horodatage (timestamp) en utilisant la méthode valueOf() de la classe java.sql.Timestamp. Il s'agit d'une méthode simple et il n'est pas nécessaire d'écrire un code complexe.
import java.text.SimpleDateFormat;
import java.sql.Timestamp;
import java.util.Date;
public class StringToTimestamp {
public static void main(String[] args) throws Exception {
// date in string format
String stringDate = "2021-01-07 02:02:16.172";
try {
// converting string date to timestamp using valueOf() method
java.sql.Timestamp timestamp = java.sql.Timestamp.valueOf(stringDate);
System.out.println(timestamp);
} catch(Exception e) {
System.out.println(e);
}
}
}
Compiler et exécuter le programme
Ouvrez le terminal et accédez au répertoire ~/project/. Utilisez la commande suivante pour compiler puis exécuter le code :
javac StringToTimestamp.java && java StringToTimestamp
Gérer un format de date incorrect
Si la chaîne de caractères est dans un format incorrect, vous obtiendrez une erreur d'exception : java.text.ParseException: Unparseable date:. Pour gérer cette erreur, nous pouvons ajouter un bloc catch pour afficher un message d'erreur.
import java.text.SimpleDateFormat;
import java.sql.Timestamp;
import java.util.Date;
public class StringToTimestamp {
public static void main(String[] args) throws Exception {
// date in string format
String stringDate = "2021-01-07 02:02:16";
try {
// creating date format
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
// parsing string to date using parse() method
Date parsedDate = dateFormat.parse(stringDate);
// finally creating a timestamp
Timestamp timestamp = new java.sql.Timestamp(parsedDate.getTime());
System.out.println(timestamp);
} catch(Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
Convertir le temps Epoch en horodatage (timestamp)
Convertissez le temps Epoch en horodatages (timestamps) en utilisant le code suivant :
import java.sql.Timestamp;
public class StringToTimestamp {
public static void main(String[] args) throws Exception {
// epoch time
long epochTime = 1609934536172L;
try {
// create Timestamp object
Timestamp timestamp = new Timestamp(epochTime);
System.out.println(timestamp);
} catch(Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
Convertir un horodatage (timestamp) en chaîne de caractères
Convertissez un horodatage (timestamp) au format chaîne de caractères en utilisant SimpleDateFormat.
import java.text.SimpleDateFormat;
import java.sql.Timestamp;
public class StringToTimestamp {
public static void main(String[] args) throws Exception {
// timestamp
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
try {
// create SimpleDateFormat object
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
// format Timestamp object
String formattedDate = dateFormat.format(timestamp);
// print formatted date
System.out.println(formattedDate);
} catch(Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
Utilisation de la classe Calendar
Au lieu de SimpleDateFormat, nous pouvons également utiliser la classe Calendar pour convertir une date sous forme de chaîne de caractères en horodatage (timestamp).
import java.util.Calendar;
import java.sql.Timestamp;
public class StringToTimestamp {
public static void main(String[] args) throws Exception {
// string date
String stringDate = "2021-01-07 02:02:16.172";
try {
// create Calendar object
Calendar calendar = Calendar.getInstance();
// set calendar date with string date
calendar.setTime(new java.text.SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS").parse(stringDate));
// convert calendar to timestamp
java.sql.Timestamp timestamp = new java.sql.Timestamp(calendar.getTimeInMillis());
System.out.println(timestamp);
} catch(Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
Utilisation de la classe ZonedDateTime
Nous pouvons également convertir une date sous forme de chaîne de caractères en horodatage (timestamp) en utilisant la classe ZonedDateTime.
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.sql.Timestamp;
public class StringToTimestamp {
public static void main(String[] args) throws Exception {
// string date
String stringDate = "2021-01-07 02:02:16.172";
try {
// create DateTimeFormatter object and specify the format of the string date
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
// create ZonedDateTime object and parse the string date
ZonedDateTime zonedDateTime = ZonedDateTime.parse(stringDate, formatter.withZone(ZoneId.systemDefault()));
// convert ZonedDateTime to timestamp
Timestamp timestamp = Timestamp.valueOf(zonedDateTime.toLocalDateTime());
System.out.println(timestamp);
} catch(Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
Exécuter le programme
Ouvrez le terminal et accédez au répertoire ~/project/. Utilisez la commande suivante pour compiler puis exécuter le code :
javac StringToTimestamp.java && java StringToTimestamp
Résumé
Dans ce laboratoire (lab), nous avons appris à convertir une date sous forme de chaîne de caractères (String) en un horodatage (Timestamp) en Java en utilisant différentes méthodes, notamment les classes SimpleDateFormat, Timestamp, Date, Calendar et ZonedDateTime. Les méthodes utilisant SimpleDateFormat et Timestamp sont les plus faciles à implémenter, tandis que la méthode utilisant ZonedDateTime est la plus complexe mais offre la plus grande flexibilité.



