Java How to get date format : dd/MM/yyyy HH:mm:ss.SS” with Date variable
If you want to store the hours, minutes and seconds, you have to use DateTime or LocalDateTime type instead of java.util.Date. Date only stores the year, month and day.
Then, you can use a formatter. For example:
public DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss.SS");
Check format of dateTime matches custom format (dd/MM/yyyy HH:mm:ss) - Java
I’d go for this in the following way:
private static final DateTimeFormatter PARSER
= DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss", Locale.ROOT);
@Test
public void correctFormatReceived() {
String dateTime = "10/18/2021 17:18:53"; // get from JSON
LocalDateTime.parse(dateTime, PARSER);
}
LocalDateTime.parse()
will throw a DateTimeParseException
if the format is incorrect, which JUnit or your test runner will then report.
If you want strict validation of the date and time value (detect if they send February 29 in a non-leap year, for example), specify so on the formatter:
private static final DateTimeFormatter PARSER
= DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss", Locale.ROOT)
.withResolverStyle(ResolverStyle.STRICT);
If you want to distinguish clearer between an incorrect format and your test failing to run to completion, catch the exception and declare a test failure:
try {
LocalDateTime.parse(dateTime, PARSER);
} catch (DateTimeParseException dtpe) {
Assert.fail(dtpe.toString());
}
What went wrong in your test?
As others have said in comments, in Java, a String
can never be equal to a LocalDateTime
. So your Assert.assertEquals(parsedDateTime, dateTime);
would fail under all circumstances. Also, being able to parse the string at all is enough to determine that the specified format is as expected; so in your test, you don’t need to test for any equality.
get current date time in yyyy-MM-dd hh.mm.ss format
You aren't parsing anything, you are formatting it. You need to use DateTimeFormatter#print(ReadableInstant)
.
DateTime now = new org.joda.time.DateTime();
String pattern = "yyyy-MM-dd hh.mm.ss";
DateTimeFormatter formatter = DateTimeFormat.forPattern(pattern);
String formatted = formatter.print(now);
System.out.println(formatted);
which prints
2013-12-16 11.13.24
This doesn't match your format, but I'm basing it on your code, not on your expected output.
Java convert DateTime from yyyy-MM-dd HH:mm:ss.SSSSSSS to yyyy-MM-dd HH:mm:ss.S or from yyyy-MM-dd HH:mm:ss.SSSSSSS to yyyy-MM-dd HH:mm:ss.SSS
So, I started out with something like...
String text = "2021-03-10 16:37:02.4230000";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSSS");
LocalDateTime ldt1 = LocalDateTime.parse("2021-03-10 16:37:02.4230000", formatter);
DateTimeFormatter shortFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S");
System.out.println(shortFormatter.format(ldt1));
LocalDateTime ldt2 = LocalDateTime.parse("2021-03-10 16:39:51.0000000", formatter);
System.out.println(shortFormatter.format(ldt2));
Which prints out ...
2021-03-10 16:37:02.4
2021-03-10 16:39:51.0
Hmmm , not quite what we're looking for.
Lucky for us, there's the DateTimeFormatterBuilder
class. So next, I tried something like...
DateTimeFormatter toFormatter = new DateTimeFormatterBuilder()
.appendPattern("yyyy-MM-dd HH:mm:ss")
.appendFraction(ChronoField.MILLI_OF_SECOND, 1, 9, true)
.toFormatter();
System.out.println(toFormatter.format(ldt1));
System.out.println(toFormatter.format(ldt2));
Which prints out ...
2021-03-10 16:37:02.423
2021-03-10 16:39:51.0
Success /p>
Now, please note, I've not really used DateTimeFormatterBuilder
before, so there might be some other, really super awesome cool way to achieve the same or better result, but hay, it's a nice start
Convert date object in dd/mm/yyyy hh:mm:ss format
You can fully format the string as mentioned in other posts. But I think your better off using the locale functions in the date object?
var d = new Date("2017-03-16T17:46:53.677"); console.log( d.toLocaleString() );
How to format a Date in MM/dd/yyyy HH:mm:ss format in JavaScript?
Try something like this
var d = new Date,
dformat = [d.getMonth()+1,
d.getDate(),
d.getFullYear()].join('/')+' '+
[d.getHours(),
d.getMinutes(),
d.getSeconds()].join(':');
If you want leading zero's for values < 10, use this number extension
Number.prototype.padLeft = function(base,chr){
var len = (String(base || 10).length - String(this).length)+1;
return len > 0? new Array(len).join(chr || '0')+this : this;
}
// usage
//=> 3..padLeft() => '03'
//=> 3..padLeft(100,'-') => '--3'
Applied to the previous code:
var d = new Date,
dformat = [(d.getMonth()+1).padLeft(),
d.getDate().padLeft(),
d.getFullYear()].join('/') +' ' +
[d.getHours().padLeft(),
d.getMinutes().padLeft(),
d.getSeconds().padLeft()].join(':');
//=> dformat => '05/17/2012 10:52:21'
See this code in jsfiddle
[edit 2019] Using ES20xx, you can use a template literal and the new padStart
string extension.
const dt = new Date();
const padL = (nr, len = 2, chr = `0`) => `${nr}`.padStart(2, chr);
console.log(`${
padL(dt.getMonth()+1)}/${
padL(dt.getDate())}/${
dt.getFullYear()} ${
padL(dt.getHours())}:${
padL(dt.getMinutes())}:${
padL(dt.getSeconds())}`
);
Java format yyyy-MM-dd'T'HH:mm:ss.SSSz to yyyy-mm-dd HH:mm:ss
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
SimpleDateFormat output = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date d = sdf.parse(time);
String formattedTime = output.format(d);
This works. You have to use two SimpleDateFormats, one for input and one for output, but it will give you just what you are wanting.
Related Topics
Splitting a Java String by the Pipe Symbol Using Split("|")
How Can an App Use Files Inside the Jar For Read and Write
Getting the Ip Address of the Current Machine Using Java
Get a List of All Threads Currently Running in Java
Swing Animation Running Extremely Slow
Why Won't Eclipse Oxygen Start (For the First Time)
How to Convert Json to a Hashmap Using Gson
How to Dynamically Compile and Load External Java Classes
"Expected Begin_Object But Was String At Line 1 Column 1"
Difference Between Applicationcontext.Xml and Spring-Servlet.Xml in Spring Framework
How to Address Unchecked Cast Warnings
Resizing Issue With Canvas Within Jscrollpane Within Jsplitpane