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?
Advertisement
Answer
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.