Getting inconsistent results with SimpleDateFormatter - java

I am running below snippet and I am getting inconsistent resluts
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-M-dd HH:mm:ss.SSS");
Date date;
date = inputFormat.parse("2020-6-30 11:45:45. 123");
SimpleDateFormat outputFormat = new SimpleDateFormat("MM-dd-yy hh:mm:ss. SSS");
System.out.println(outputFormat.format(date));//06-30-20 11:45:45. 123 is the output
Snippet 2:
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-M-dd HH:mm:ss.SSSSSS");
Date date;
date = inputFormat.parse("2020-6-30 11:45:45. 123456");
SimpleDateFormat outputFormat = new SimpleDateFormat("MM-dd-yy hh:mm:ss. SSSSSS");
System.out.println(outputFormat.format(date));//06-30-20 11:47:48. 000456 is output
snippet 3:
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-M-dd HH:mm:ss.SSSSSSSSS");
Date date;
date = inputFormat.parse("2020-6-30 11:45:45. 123456789");
SimpleDateFormat outputFormat = new SimpleDateFormat("MM-dd-yy hh:mm:ss. SSSSSSSSS");
System.out.println(outputFormat.format(date));//07-01-20 10:03:21. 000000789 is output
I believe the fraction seconds should be same before and after conversion. How can I achieve consistent results

The first one is correct, because your milliseconds are between 0 - 999. The second and third one are technically also correct, except your 123456 milliseconds are converted in 123 seconds + 456 milliseconds, which results in a time of +2 mins 03 secs.
So instead of trying to fix the output of simple date format, you have to fix the way you handle the input. Simple date format can not parse anything smaller than milliseconds. If you provide it with a number bigger than 999 milliseconds, it affects the seconds and so on...

Related

How do I format JDateChooser into dd-mm-yyyy?

I am trying to output the current date format into:
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");, but it is outputting like this:
Fri Dec 02 14:03:59 AEST 2016
Here is my code:
JDateChooser datePurchased = new JDateChooser();
DateFormat dateFormat = new SimpleDateFormat("dd-mm-yyyy");
Date newDate = new Date();
datePurchased.setDate(newDate);
I am now printing the result like this:
System.out.println(newDate.toString());
But this does not print out what I want, as per above.
My goal output is: 02/12/2016, how do I go about doing this, I've tried looking around but I cannot find the likes to solve my problem.
Thank you in advance.
The first part is simple enough, a Date is a representation in epoch time and doesn't have a modifiable format. Instead, you format it when you want to display it (or otherwise obtain a String representation). Additionally, you need M for months (m is minutes) and if you want / use that instead of -. For example,
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date newDate = new Date();
System.out.println(dateFormat.format(newDate));
You are printing the date but no using the formatter, you need to do:
String pattern = "dd-MM-yyyy";
DateFormat formatter = new SimpleDateFormat(pattern);
System.out.println(formatter.format(newDate));
edit:
if your goal output is: 02/12/2016
then in the pattern in the format incorrect, you will need to use slash and not hyphens
use instead dd/mm/yyyy
Use this simple code:
bill_date.setDateFormatString("yyyy-MM-dd");
In here bill_date is instance of the JDateChooser.

SimpleDateFormat parsing date string incorrectly

I'm trying to parse a String into a Date and then format that Date into a different String format for outputting.
My date formatting code is as follows:
SimpleDateFormat dateFormatter = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat dateParser = new SimpleDateFormat("d/M/yyyy h:m:s a");
String formattedDocumentDate = dateFormatter.format(dateParser.parse(sysObj.getString("document_date")));
The result of sysObj.getString("document_date") is 1/31/2013 12:00:01 AM. And when I check the value of formattedDocumentDate I get 01/07/2015.
Any help is much appreciated.
You are parsing days 31 as months. SimpleDateFormat tries to give you a valid date. Therefore It adds to 1/0/2013 31 months. This is 2 years and 7 month. So you get your result 01/07/2015. So SimpleDateFormat works correct.
One solution for you is to change your date pattern to M/d/yyyy h:m:s a or your input data.
To avoid these tries you have to switch off SimpleDateFormat lenient mode. Then you will get an exception if the format does not fit.
It looks like your input format is actually months first, then days. So should be "MM/dd/yyyy".
So:
SimpleDateFormat dateFormatter = new SimpleDateFormat("dd/M/yyyy");
SimpleDateFormat dateParser = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");
String formattedDocumentDate = dateFormatter.format(dateParser.parse(sysObj.getString("document_date")));
Another example like this
SimpleDateFormat sdfInput = new SimpleDateFormat("yyyyMMdd");
System.out.println("date is:"+new java.sql.Date( sdfInput.parse("20164129").getTime() ));
Output is: 2019-05-29
I expect to throw parse exception but not (41)is not a valid month value.
on the other hand if I gave 20170229, system can recognize the February of 2017 doesn't have a lap year and return 2017-03-01 interesting.

Date to string is not correnct

Probably there will be simply and fast answer but I still cant find out why is the result of
Date date = new Date(60000); //one min.
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
String dateStr = dateFormat.format(date);
dateStr - 01:01:00
Still one hour more. Time zone? How can I set it without it? Thanks.
Date represents a specific moment in time, not a duration. new Date(60000) does not create "one minute". See the docs for that constructor:
Initializes this Date instance using the specified millisecond value. The value is the number of milliseconds since Jan. 1, 1970 GMT.
If you want "one minute from now" you'll probably want to use the Calendar class instead, specifically the add method.
Update:
DateUtils has some useful methods that you might find useful. If you want the elapsed time in HH:mm:ss format, you might try DateUtils.formatElapsedTime. Something like:
String dateStr = DateUtils.formatElapsedTime(60);
Note that the 60 is in seconds.
Three ways to use java.util.Date to specify one minute:
1. Using SimpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")) as shahtapa said:
Date date = new Date(60*1000); //one min.
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
String dateStr = dateFormat.format(date);
System.out.println("Result = " + dateStr); //Result should be 00:01:00
2. Using java.util.Calendar as kabuko said:
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.set(Calendar.MINUTE,1); //one min.
Date date = calendar.getTime();
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
String dateStr = dateFormat.format(date);
System.out.println("Result = " + dateStr); //Result should be 00:01:00
Other calendar.set() statements can also be used:
calendar.set(Calendar.MILLISECOND,60*1000); //one min.
calendar.set(1970,0,1,0,1,0); //one min.
3. Using these setTimeZone and Calendar ideas and forcing Calendar to
UTC Time-Zone
as Simon Nickerson said:
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
calendar.clear();
calendar.set(Calendar.MINUTE,1); //one min.
Date date = calendar.getTime();
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
String dateStr = dateFormat.format(date);
System.out.println("Result = " + dateStr); //Result should be 00:01:00
Note: I had a similar issue: Date 1970-01-01 was in my case -3 600 000 milliseconds (1 hour late) java.util.Date(70,0,1).getTime() -> -3600000
I recommend to use TimeUnit
"A TimeUnit represents time durations at a given unit of granularity and provides utility methods to convert across units, and to perform timing and delay operations in these units. A TimeUnit does not maintain time information, but only helps organize and use time representations that may be maintained separately across various contexts. A nanosecond is defined as one thousandth of a microsecond, a microsecond as one thousandth of a millisecond, a millisecond as one thousandth of a second, a minute as sixty seconds, an hour as sixty minutes, and a day as twenty four hours."
http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/TimeUnit.html
Date date = new Date(); // getting actual date
date = new Date (d.getTime() + TimeUnit.MINUTES.toMillis(1)); // adding one minute to the date

How to convert Standard Date into minutes in java?

How to convert standard output of date into number of minutes?
I have output from my command as:
Mon Mar 4 12:33:58 2013
and I need to convert it into number of minutes say minutes1.
because I have a code which gives number of minutes for current time and the code is:
public class DateToMinutes {
public static void main(String[] args) {
Date date = new Date();
long now = ((date.getTime()) / (60000));
System.out.println("Total Minutes are " + now);
}
}
the output of this will be in minutes say minutes2.
I need to compare both minutes1 and minutes2.
since I am unable to convert Standard date into minutes1, it's not possible right now.
look at parse method of SimpleDateFormat, there you'll find formats used for converting dates.
Javadocs here
In your case something like this should work:
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM d HH:mm:ss yyyy");
Date theDate = sdf.parse ("Mon Mar 4 12:33:58 2013");
long minutes2 = theDate.getTime() / 60000;
Use a simpledate formatter.
DateFormat formatter = new SimpleDateFormat("mm");
Date one = ...
Date two = ...
formatter.format( one) ); // only the minutes remain
formatter.format( two) ); // only the minutes remain
// do whatever you want.
Determining minutes1 is parsing a date and transforming it.
Related issues can be found here and here.
This should do the job based on your description of the date format:
SimpleDateFormat yourStandardDateFormat = new SimpleDateFormat("EEE MMM dd kk:mm:ss yyyy");
Date date = yourStandardDateFormat.parse( stringRepresentingDate );
long minutes1 = date.getTime() / 60000l;
For reference, see SimpleDateFormat documentation

Parsed date has minute difference

So I am trying to parse a date string in Java. I am getting the correct hours back but the minutes seem to be out by about 5-10. I am showing my code below along with the input string and the date Objects toString() output.
Any ideas where I am going wrong? This is on Android so I would prefer not to use JodaTime.
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
Date date = sdf.parse(input);
return date;
Input String = 2012-11-07T12:47:05.0581816Z
Date toString() = Wed Nov 07 12:56:46 GMT 2012 (Milliseconds = 1352293006816)
You are trying to parse a date with microsecond precision as millisecond precision.
0581816 is the number of milliseconds added to the time 12:47:05, not, as you probably expect, a decimal fraction of a second.
Since the precision below millisecond cannot be represented by java.util.Date, the simplest option would be to truncate the decimal fraction and adjust the date format, as follows:
final DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
String input = "2012-11-07T12:47:05.058234234Z";
input = input.replaceFirst("(?<=\\.\\d{3})\\d+", "");
System.out.println(input);
System.out.println(sdf.parse(input));
Please make sure you are using the same time zone while converting a String to a date object and vice-versa

Categories

Resources