Reputation: 107
I have a timestamp saved in Azure SQL Database in the format of 2004-09-23 10:52:00. When I fetch the value, I am using sqlrowset where I am using getString("last_updated_user")
and getting output like this "2004-09-23 10:52:00.0". When I tried using getTimeStamp("last_updated_user")
, I am getting in microseconds. Can someone help me on formatting it to "2004-09-23 10:52:00" based on some in-built functions like .format or something and not by just removing the decimal by replace or substring?
Upvotes: 1
Views: 210
Reputation: 86232
I am guessing a bit here since I don’t know Azure SQL database. What you are reporting sounds like you are having an SQL timestamp
or equivalent in your database. Assuming that your JDBC driver is JDBC 4.2 compliant get a LocalDateTime
(not a string) from your database:
LocalDateTime lastUpdatedUser
= sqlrowset.getObject("last_updated_user", LocalDateTime.class);
I have further assumed that sqlrowset
is a javax.sql.RowSet
. To format into your desired string use a formatter like this one:
private static final DateTimeFormatter FORMATTER
= DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
Now we may do:
System.out.println("LocalDateTime retrieved: " + lastUpdatedUser);
String formatted = lastUpdatedUser.format(FORMATTER);
System.out.println("Formatted: " + formatted);
Example output:
LocalDateTime retrieved: 2004-09-23T10:52 Formatted: 2004-09-23 10:52:00
Upvotes: 2
Reputation: 79035
Solution using java.time
, the modern Date-Time API:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String d = "2004-09-23 10:52:00.0";
DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern("u-M-d H:m:s.S", Locale.ENGLISH);
LocalDateTime ldt = LocalDateTime.parse(d, dtfInput);
DateTimeFormatter dtfOutput = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss", Locale.ENGLISH);
String str = ldt.format(dtfOutput);
System.out.println(str);
}
}
Output:
2004-09-23 10:52:00
Learn more about the modern Date-Time API* from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
Upvotes: 2