Exact string to date and keep original format [duplicate] - java

This question already has answers here:
How to properly format the date?
(5 answers)
Get Date type object in format in java
(6 answers)
display Java.util.Date in a specific format
(11 answers)
Closed 1 year ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
I have looked around for help on this, but again, it's just one of those things that I cannot find a suitable answer to my specific issue.
Here's 2 very detailed (and helpful) SO posts that I've looked at:
Change date format in a Java string
Java string to date conversion
This is what I have:
//Date Formatter
SimpleDateFormat dateFormatter1 = new SimpleDateFormat("yyyy-MM-dd", new Locale("EN"));
SimpleDateFormat dateFormatter2 = new SimpleDateFormat("dd MMMM yyyy", new Locale("EN"));
//Convert to Date
Date dateToParse = dateFormatter1.parse("2024-01-01");
//Format OUTPUT date
String dateAsString = dateFormatter1.format(dateToParse);
System.out.println(dateAsString); //01 January 2024
//Convert OUTPUT date from STRING to DATE
Date dateToReturn = dateFormatter1.parse(dateAsString);
System.out.println(dateToReturn.toString()); //Mon Jan 01 00:00:00 SAST 2024
Note:
I used both DateFormatter and SimpleDateFormatter but got the same output.
The outputs are very different and what I am trying to achieve is to have my String created as a Date object in the exact same format.
I feel I am missing something but I just cannot figure out what.
The code I provided is a snippet from a bigger function that returns type Date
The function wasn't created by myself, I'm picking up from where someone else left off

Whenever you call a .toString() method on a Date, then the DateFormatter is not taken into account. The format of date you get is just a matter of default toString implementation of Date class.
To use formatter while printing, try something like this (instead of the last line in your snippet):
System.out.println(dateFormatter1.format(dateToReturn));

Date.toString() returns always returns a string in the format dow mon dd hh:mm:ss zzz yyyy.
You'll need to reuse the formatter's format method to get the initial string you expect

Related

How to print UTC or GMT using SimpleDateFormat? [duplicate]

This question already has answers here:
Convert Java Date to UTC String
(7 answers)
How do you format current system datetime as UTC using String.format in Java?
(2 answers)
How to get UTC+0 date in Java 8?
(5 answers)
Closed last month.
This post was edited and submitted for review last month and failed to reopen the post:
Original close reason(s) were not resolved
I am trying to print a date in this format:
2023-01-11 09:25:52 UTC
But when I use date format:
yyyy-MM-dd HH:mm:ss Z
I get:
2023-01-11 09:29:25 +0100
While searching by existing question in stack overflow, I found similar questions but not with this exact format with "UTC" at the end. I found one that provided a solution to add the format as yyyy-MM-dd HH:mm:ss 'UTC' but then it would force the a GMT value to wrongly show UTC at the end.
Most of the answers explain how to get UTC value, but not how to print in this format
2023-01-11 09:25:52 UTC
Some solutions were also suggesting to use something else than SimpleDateFormat.
This question was marked as duplicated, but none of the post that were supposed to be duplicated had the info that I wanted.
Use a lowercase z instead of Z to get the offset instead of the id. And you have to set the time zone using simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")).
Example:
Date date = new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(simpleDateFormat.format(date)); // 2023-01-11 08:41:17 UTC
If you create an instance of simpleDateFormat with yyyy-MM-dd HH:mm:ss Z date format is incorrect change to capital Z to small z,
then it works as expected.
2023-01-11 09:25:52 UTC

How to Parse Date in Java in Given Format? [duplicate]

This question already has answers here:
Java string to date conversion
(17 answers)
Closed 5 years ago.
I try to use java.util.Date date = Date.from( Instant.parse(minDates)); to parse the date string given in format Wed Jan 17 2001 00:00:00 GMT 0530.
I am not able to figure out, how to do that in JAVA.
The want to convert the given date string in given format
2013-05-22T00:00:00
May be i am not able to figure it out, properly. If someone have way to do that suggest me in Java Only.
Here is the solution:
String dateToParse = "Wed Jan 17 2001 00:00:00 GMT 0530";
SimpleDateFormat in = new SimpleDateFormat("EEE MMM dd YYYY HH:mm:ss");
SimpleDateFormat out = new SimpleDateFormat("YYYY-MM-dd'T'HH:mm:ss");
Date date = in.parse( dateToParse );
System.out.println( out.format( date ) );
It will work if all dates are in the same timezone (GMT 0530)
Else it should be modified to support it, but I suppose you have the same timezone.
You can do that by using SimpleDateFormat 'parse' API.
You can initialize your SimpleDateFormat with any valid time format such as yyyy-MM-dd HH:mm:ss z and then parse any string which adheres to this format.
reff. to http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
One addition tip, use JodaTime as the Date and SDF in Java are getting deprecated: http://www.joda.org/joda-time/
If you are using Java 8+, You can use java.time.OffsetDateTime (or Instant...) instead of java.util.Date, which is incredibly easy.
OffsetDateTime odt = OffsetDateTime .parse("2013-05-22T00:00:00", DateTimeFormatter.ISO_LOCAL_DATE_TIME);
Note that the second argument is optional in this case but you could have to specify one (with timezone id for example).
There is a solution without external which works with older version of Java and that manages timezones well. It consists of using JAXB's DataTypeConverter.
Date date = javax.xml.bind.DatatypeConverter.parseDateTime("2013-05-22T00:00:00+01:00").getTime();
Note that DatatypeConverter.parseDateTime returns a Calendar. You just need to call its getTime() method to convert is to a Date.

Android timestamp to local user time or date [duplicate]

This question already has answers here:
Unix epoch time to Java Date object
(7 answers)
Closed 5 years ago.
How can I convert minutes from Unix timestamp to date and time in java? For example, timestamp 1372339860 correspond to Thu, 27 Jun 2013 13:31:00 GMT.
I want to convert 1372339860 to 2013-06-27 13:31:00 GMT.
Edit: Actually I want it to be according to US timing GMT-4, so it will be 2013-06-27 09:31:00.
You can use SimlpeDateFormat to format your date like this:
long unixSeconds = 1372339860;
// convert seconds to milliseconds
Date date = new java.util.Date(unixSeconds*1000L);
// the format of your date
SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
// give a timezone reference for formatting (see comment at the bottom)
sdf.setTimeZone(java.util.TimeZone.getTimeZone("GMT-4"));
String formattedDate = sdf.format(date);
System.out.println(formattedDate);
The pattern that SimpleDateFormat takes if very flexible, you can check in the javadocs all the variations you can use to produce different formatting based on the patterns you write given a specific Date. http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
Because a Date provides a getTime() method that returns the milliseconds since EPOC, it is required that you give to SimpleDateFormat a timezone to format the date properly acording to your timezone, otherwise it will use the default timezone of the JVM (which if well configured will anyways be right)
Java 8 introduces the Instant.ofEpochSecond utility method for creating an Instant from a Unix timestamp, this can then be converted into a ZonedDateTime and finally formatted, e.g.:
final DateTimeFormatter formatter =
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
final long unixTime = 1372339860;
final String formattedDtm = Instant.ofEpochSecond(unixTime)
.atZone(ZoneId.of("GMT-4"))
.format(formatter);
System.out.println(formattedDtm); // => '2013-06-27 09:31:00'
I thought this might be useful for people who are using Java 8.
You need to convert it to milliseconds by multiplying the timestamp by 1000:
java.util.Date dateTime=new java.util.Date((long)timeStamp*1000);

Converting String to Timestamp, SimpleDateFormat, Omiting fields [duplicate]

This question already has answers here:
Convert String to java.util.Date
(4 answers)
Closed 7 years ago.
I read more questions on the web but I dont' find a solution yet.
I have a String like "14/05/1994", exactly in this format.
I need to covert it into java.util.Date in the same format.
I tried:
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Date dataFrom = new Date();
dataFrom = df.format("14/05/1994");
But the result is: Sat May 14 00:00:00 CET 1994
It's possibile have as a result: 14/05/1994 not as a String, but as java.util.Date?
A java.util.Date doesn't have a format. It's just a date.
When you print it out, e.g. using toString(), it uses a default format, which is what you're seeing. But you have that date.
Date dataFrom = new Date();
dataFrom = df.format("14/05/1994");
I don't think that can be your code because DateFormat.format accepts a Date and returns a String, not the other way around. You might mean df.parse, which would get you the results you describe. But if you take your SimpleDateFormat and use its format method on the Date, then you should get back out 14/05/1994 as you want. A java.util.Date doesn't have a format, though.

Convert String to Date not working properly [duplicate]

This question already has answers here:
java date problem in parsing
(4 answers)
Closed 7 years ago.
I am getting a date by ajax in String format. But it is getting changed when I am converting it to date by SimpleDateFormat. The month is always changed to Jan. I am worried only about the month change.My code is given below
String appointmentDate = request.getParameter("appointmentDate");
System.out.println(" appointment date in String format "+appointmentDate);
Here I am getting the date correctly(16/12/2015). But when I am changing it to Date format it is getting changed(Fri Jan 16 00:12:00 IST 2015). Whatever I input the month, say August, May, June, I am always getting month Jan.
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy");
Date parsedDate = dateFormat.parse(appointmentDate);
System.out.println(" appointment date in DATE format "+parsedDate);
Please help me out. Thanks in advance.
As per the JavaDoc, lower case m denotes minutes, not months.
Changing your expression to dd/MM/yyyy should fix the issue.

Categories