Convert Date string into another string with different format - java

I'm quite new to the Java and for the use case I would like to know how to convert String "2023-02-01" into "02012023"
I had troubles understanding the correct usage of SimpleDateFormat for this case
So far I tried nothing

SimpleDateFormat is legacy now, try to use the modern java.time library instead:
String newStringDate = LocalDate.parse("2023-02-01")
.format(DateTimeFormatter.ofPattern("MMdduuuu"));

Related

SimpleDateFormat vs LocalDateTime - Parsing Differences with postfixes [duplicate]

I'm retrofitting old some SimpleDateFormat code to use the new Java 8 DateTimeFormatter. SimpleDateFormat, and thus the old code, accepts strings with stuff in them after the date like "20130311nonsense". The DateTimeFormat I created throws a DateTimeParseException for these strings, which is probably the right thing to do, but I'd like to maintain compatibility. Can I modify my DateTimeFormat to accept these strings?
I'm currently creating it like this:
DateTimeFormatter.ofPattern("yyyyMMdd")
Use the parse() method that takes a ParsePosition, as that one doesn't fail when it doesn't read the entire text:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
TemporalAccessor parse = formatter.parse("20140314 some extra text", new ParsePosition(0));
System.out.println(LocalDate.from(parse));
The ParsePosition instance that you pass will also be updated with the point at which the parsing stopped, so if you need to do something with the leftover text then it will be useful to assign it to a variable prior to calling parse.

convert string timestamp to ISO 8601 compliant string

I have a timestamp and offset in string format as shown below in two different variables:
01/14/2016 07:37:36PM
-08:00
I want to convert above timestamp into ISO 8601 compliant String, with milliseconds and timezone so it should look like this after conversion:
2016-01-14T19:37:36-08:00
How can I do that? I am using jodatime library.
The newer java.time classes work so well with ISO 8601 strings.
String dateTimeString = "01/14/2016 07:37:36PM";
String offsetString = "-08:00";
LocalDateTime dateTime = LocalDateTime.parse(dateTimeString,
DateTimeFormatter.ofPattern("MM/dd/uuuu hh:mm:ssa"));
ZoneOffset offset = ZoneOffset.of(offsetString);
String formattedTimestamp = dateTime.atOffset(offset).toString();
System.out.println(formattedTimestamp);
This prints
2016-01-14T19:37:36-08:00
Stay away from outdated classes like SimpleDateFormat.
What is offsetString is not present? I understand that in this case you want an offset of Z for UTC. For example like this:
ZoneOffset offset;
if (offsetString == null) {
offset = ZoneOffset.UTC;
} else {
offset = ZoneOffset.of(offsetString);
}
String formattedTimestamp = dateTime.atOffset(offset).toString();
With a null offsetString we now get
2016-01-14T19:37:36Z
The classes in java.time (of which I’m using but a few) are described in JSR-310 and come built-in with Java 8. What if you would like to use them with Java 6 or 7? You get the ThreeTen Backport (link below). It gives you the majority of the classes for Java 6 and 7. I’m not perfectly happy to tell you you need an external library, but in this case it’s only until you move to Java 8. I hope you will soon.
I am sure it can be done with JodaTime too, but I haven’t got experience with it, so cannot give you the details there. What I do know, I have read the the folks behind JodaTime now recommend you move over to java.time instead. So I am asking you to swap one external library for a newer (and supposedly better) one. In itself I’m not unhappy with that. Only if you already have a codebase that uses JodaTime, it’s not really trivial.
Link: ThreeTen Backport
You can find more examples in section Examples at :- http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
String string2 = "2001-07-04T12:08:56.235-07:00";
Date result2 = df2.parse(string2);

Java Equivalent to .NET's DateTime.Parse?

I'm working on a java class that I will use with Pervasive Data Profiler that needs to check if a Date String will work with .NET's DateTime.Parse.
Is there an equivalent class or 3rd party library that can give me this functionality that is very close to .NET's DateTime.Parse?
I would need it to be able to handle a broad range of date formats.
ex. "12/20/2008", "1/1/08", "5/10/2009 12:46:00 AM", "5/10/2009 17:46:00"
See parse method in DateFormat Class. Here is a sample
DateFormat df = new SimpleDateFormat ("yyyy-MM-dd");
Date date = df.parse("2001-01-01");
Check the DateFormat.parse(String) methods of the DateFormat class.
Also, the class Date has two deprecated methods that parse strings into Date objects, however the use of the Date class in general is not recommended. It has been replaced by the Calendar class.
Use DateFormat:
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date = format.parse("2010-03-15");
SimpleDateFormat (is very handy. But... if you really want to use something more powerful -and consider it's really worth- you can use Joda Time. It's a very powerful, yet easy-to-use library. Indeed there's a proposal to make a new standard library very similar to it.

How to convert a date String into the right format in Java?

Can somebody please explain to me how I can convert
2009-10-27 14:36:59.580250
into
27.10.2009, 14:36 ?
The first date is available as a string and the second one should be a string as well ;) Up to now I'm not so into date conversion within Java...
Thanks in advance!
You can use java.text.SimpleDateFormat for this. First step is to parse the first string into a java.util.Date object using SimpleDateFormat based on the pattern of the first string. Next step is to format the obtained java.util.Date object into a string based on the pattern of the second string. For example:
String datestring1 = "2009-10-27 14:36:59.580250";
Date date1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(datestring1);
String datestring2 = new SimpleDateFormat("dd.MM.yyyy HH:mm").format(date1);
System.out.println(datestring2);
Edit: I've removed the .SSSSSS part from the first pattern because it failed. But in my opinion it should in theory have worked with "yyyy-MM-dd HH:mm:ss.SSS" and "yyyy-MM-dd HH:mm:ss.SSSSSS" as well, but it is calculating them as seconds! I consider this as a buggy implementation in SimpleDateFormat. The JodaTime handles the millis/micros perfectly with those patterns.
You can use SimpleDateFormat. Although there's no format specification for micro-seconds (the last fragment of your input), you can make use of the fact that the parser ignores the rest of the string if it has already managed to match the configured pattern:
SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd HH:mm");
SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy HH:mm");
System.out.println(formatter.format(parser.parse("2009-10-27 14:36:59.580250")));
The parser will in this case simply ignore the last part ":59.580250" of the input string.
Check out SimpleDateFormat. You can use this to both parse and format. I would suggest parsing the above into a Date object using one SimpleDateFormat, and then formatting to a String using a 2nd SimpleDateFormat.
Note that SimpleDateFormat suffers from threading issues, and so if you're using this in a threaded environment, either create new SimpleDateFormats rather than used static versions, or use the corresponding but thread-safe classes in Joda.
Keep in mind when you do this that you are losing precision. Depending on your specific application, this may or may not matter.
If you already have the original date saved somewhere, this is not an issue. However, if the source date is from a transient source (e.g., streaming in from a physical sensor of some sort), it may be a good idea to persist the interim Date object (output of SimpleDateFormat#parse(String)) somewhere.
Just thought I'd point that out.

Formatting Timestamps in Java

Is there a way to format a UTC time into any arbitrary string format I want in java? Basically I was thinking of having some class take the timestamp and I pass it is string telling it how I want it formated, and it returns the formatted string for me. Is there a way to do this?
The java.text.SimpleDateFormat class provides formatting and parsing for dates in a locale-sensitive manner.
The javadoc header for SimpleDateFormat is a good source of detailed information. There is also a Java Tutorial with example usages.
The DateFormat class or SimpleDateFormat should get you there. For example, http://www.epochconverter.com/ lists the following example to convert a epoch time to human readable timestamp with Java:
String date = new java.text.SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(new java.util.Date (epoch*1000));
Date instances are insufficient for some purposes.
Use Joda Time instead.
Joda time integrates with Hibernate and other databases.
One gotcha to be aware of is that SimpleDateFormat is NOT thread-safe. Do not put it in a static field and use it from multiple threads concurrently.

Categories