Date Formatting Issue - java

The following Java test passes on our US hosted build server. It also passes on non-US servers, e.g. in Germany. It fails on my local server, which is running in Ireland. The following code illustrates a failing test.
org.junit.ComparisonFailure: expected:<[4/6/09 11:30 AM]> but was:<[06/04/09 11:30]>
Is there a system setting I can provide to get these tests passing locally?
public void testFormattedDate() {
// Set the default time zone in case this unit test is executed in a different country
TimeZone.setDefault(TimeZone.getTimeZone(DateUtil.DEFAULT_TIMEZONE));
final Date utilDate = new Date();
utilDate.setDate(6);
utilDate.setHours(11);
utilDate.setMinutes(30);
utilDate.setMonth(3);
utilDate.setSeconds(45);
utilDate.setYear(109);
SimpleDateFormat dateFormatter = new SimpleDateFormat();
final String formattedOutput = dateFormatter.format(utilDate);
Assert.assertEquals("4/6/09 11:30 AM", formattedOutput);
}

Have to tried to provide a pattern to the SimpleDateFormat ?
SimpleDateFormat dateFormatter = new SimpleDateFormat("d/M/yy HH:mm a");

The time is correct but the SimpleDateFormat() constructor internally calls a package private construtor using Locale.getDefault(). Thus you either can provide a format of your own or provide another locale, which seems to only be possible with a custom format, i.e. using SimpleDateFormat(String pattern, Locale locale).
The problem is that SimpleDateFormat() uses a locale dependent pattern, thus the system's default locale might result in a different pattern than what you get in the USA (I assume the German server doesn't use the German locale as its default since then you should get a date like 06.04.09 11:30).

Related

SimpleDateFormat question for timezone offset +AA:BB

I am currently using the following SimpleDateFormat pattern:
String DATE_TIME_FORMAT_PATTERN = "yyyy-MM-dd'T'HH:mm:ss,SSSXXX";
This works fine, however some raspberry Pi java implementations don't recognize it properly:
timestamp 2020-01-21T09:41:45,434Z
In most cases, this won't be an issue, however the offset is buggy for some raspberry PIs; I don't want that. Is there an alternative pattern with the same offset format (+/-HH:mm) that could work? I've tried all kinds of patterns, but none seem to produce the same output.
I also used the following tool to search for such a pattern: https://javadevtools.com/simpledateformat , though it was fruitless.
NOTE: An example output of this format is 1997-07-16T19:20:30,45+01:00 , with a colon in the offset.
If you were using java.time, especially the two classes java.time.OffsetDateTime (pattern symbols are explained in this JavaDoc) and java.time.format.DateTimeFormatter, you or your Raspberry Pi would be able to correctly parse the timestamp (which has a strange format using a comma to separate fractions of second from the seconds).
The following example parses your timestamp and outputs the default format:
public static void main(String[] args) {
String timestamp = "1997-07-16T19:20:30,45+01:00";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss[,SSS]xxx");
OffsetDateTime odt = OffsetDateTime.parse(timestamp, dtf);
System.out.println(odt);
}
Output:
1997-07-16T19:20:30.450+01:00
I confirm that this is not a Pi issue. I switched my local time zone to UTC and ran the following example:
long current = System.currentTimeMillis();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss,SSSXXX");
Date date = new Date(current);
String parsed = format.format(date);
System.out.println(parsed);
2020-08-31T15:05:27,872Z
And the Z appeared, on Windows 10. I have missed that part of the ISO spec. It seems I have to workaround my tests for this situation :). Thanks everyone!

Get current date in a specific format

I am trying to retrieve the current date in the following format: 21-FEB-17.
I have the following code but it isn't the format I need. It prints out in the following format: 21-February-17.
Format formatter = new SimpleDateFormat("dd-MMMM-yy");
String today = formatter.format(new Date());
System.out.println(today);
To get the "first 3 letters" of the month, you should use
Format formatter = new SimpleDateFormat("dd-MMM-yy");
as per the Oracle documentation of SimpleDateFormat.
That will print the month in "Camel" case (i.e., "Feb"). If you want it in all uppercase, you need to do
System.out.println(today.toUpperCase());
Your format had and extra M:
Format formatter = new SimpleDateFormat("dd-MMM-yy");
String today = formatter.format(new Date());
System.out.println(today.toUpperCase());
Here is the link to help you understand better.
And to answer your question use below code.
Format formatter = new SimpleDateFormat("dd-MMM-yy");
String today = formatter.format(new Date());
System.out.println(today.toUpperCase());
This is not the answer you asked for, but it may be the answer you want. :-) As Bojan Petkovic has already said in a comment, if there’s any way you can use Java 8, you will want to use the new java.time classes:
final Locale myLocale = Locale.US;
String today = LocalDate.now()
.format(DateTimeFormatter.ofPattern("d-MMM-yy", myLocale))
.toUpperCase(myLocale);
System.out.println(today);
This prints:
22-FEB-17
You will notice I explicitly use a locale object both for the formatter and for converting to uppercase. You know best which locale you want to use. You may also leave out the locale argument in both places, then the computer’s default locale will be used (so you will get different results on different computers). For a locale neutral formatting, use Locale.ROOT (it will be rather like Locale.US).

Formating java Date with java.time.DateTimeFormatter including time offset

I am currently struggling to refactor this piece of old code to use the new java.time.format.DateTimeFormatter because it is used in our main logging component where this creates unnecessary garbage.
private String getFormattedDate(final Date date) {
// a new instance is created foreach log message
SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
return dateFormat.format(date);
}
I already tried the new ISO_INSTANT formater like:
DateTimeFormatter.ISO_INSTANT.format(date.toInstant());
but this gives (slightly) different output as before.
My test shows:
Expected: is "2013-10-22T05:23:48.397+0200"
but: was "2013-10-22T03:23:48.397Z"
So I need the time zone offset to be included in the format string as shown in Expected.
I know about the DateTimeFormatterBuilder but I didnt manage to build it in a way to get my desired format output.
How would I need to do this?
I know I can always fall back to using a single thread local SimpleDateFormat instance but I would like to use the new java.time stuff :-)
Date date = new Date();
System.out.println(DateTimeFormatter.ISO_INSTANT.format(date.toInstant()));
// output: 2015-11-22T14:46:08.776Z
System.out.println(DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(
date.toInstant().atZone(ZoneId.systemDefault())));
// output: 2015-11-22T15:46:08.776+01:00
System.out.println(DateTimeFormatter.ISO_OFFSET_DATE_TIME
.withZone(ZoneId.systemDefault())
.format(date.toInstant()));
// output: 2015-11-22T15:46:08.776+01:00

Java Server and Client Time

Please can any body help me I have been faced time related problem regarding client and server time display issue since 1 week.
Description: Actually server is located in Germany when client (example : india) try to send any message to his contacts it will show the message sending time is server time (means Germany time).But I should say local specific time.I user send any then I show message sending time like this.
public static String retrieveFullDateFromDateinAMPM ( Date date ) {
SimpleDateFormat sdf =
new SimpleDateFormat("dd/MM/yy hh:mm a", Locale.getDefault());
return sdf.format(date);
}
Here I send date value to my helper method retrieveFullDateFromDateinAMPM(Date date) and I will return the message sending time like this : return sdf.format(date); to the web page. But it shows server located time but I should need to show locale specific time. Please help me. Advanced Thanks.
First of all Date does not know anything about specific timezones. You need to call SimpleDateFormat#setTimeZone to set specific timezones.
Consider code like below setting IST (Indian Standard Time) timezone on your DateFormat instance:
DateFormat sdf = new SimpleDateFormat("dd/MM/yy hh:mm a", Locale.getDefault());
sdf.setTimeZone(TimeZone.getTimeZone("IST"));
// Will print the date-time in the IST timezone
System.out.println(sdf.format(date));
OR else format the data using current timezone of the system:
sdf.setTimeZone( TimeZone.getDefault() );
a server-side solution mandates that the server code knows about the location of the client. i assume that this information will be supplied somehow as a iso 2-letter code. the java api mandates that for the following solution to work the language must also be known. i assume that it can be derived from the country code or is expressly supplied as an iso 2-/3-letter code.
so a revised method might be:
public static String retrieveFullDateFromDateinAMPM ( Date date, String lang, String country ) {
SimpleDateFormat sdf =
new SimpleDateFormat("dd/MM/yy hh:mm a", Locale ( lang, country ) )
;
return sdf.format(date);
}
for more details see the java docs:
would it be not better to send to client always UTC ?
Client wold always have information about UTC and could convert it to local time ?
You need to set proper locale when parsing/formating a date object. If the locale is properly set in client browser, you should be able to access with javax.servlet.ServletRequest.getLocale() method.
Actually I done this from client side.Means after sending server time to client side(html, jsp....) then I write a bit of Jquery code like this.Here please convert the server date into .getTime() at your client side.(example new Date().getTime() == $('#message_creation_time').val())
<script type="text/javascript">
$(document).ready(function(){
var date = new Date(parseInt($('#message_creation_time').val()));
var localeSpecificTime = date.toLocaleTimeString().replace(/:\d+ /, ' ');
var dateString = date.toDateString();$('.message_creation_time_display').html(dateString+" "+localeSpecificTime);
});
</script>

Trying to convert yyyy-MM-ddTHH:mm:ss-07:00 to correct time in Android

Okay, so here's my issue in Android right now. On our Database there's a timestamp in this format 8/15/2013 2:00:48 PM and through a .NET WebService I get that same time like this in Android: 2013-08-15T14:00:48-07:00. Now I want to convert this format into a Date Time format that I can use for comparison (for example this webservice provides every instance where a device failed at logging in so we want to check the amount of time between occurances to see if there's any issues). Below I have this code where I'm trying to use JODA Time but it's still not returning the correct format:
public static Date convertStringToDate(String input) {
String pattern = "yyyy-MM-dd'T'HH:mm:ssZ";
DateTimeFormatter formatter = DateTimeFormat.forPattern(pattern);
DateTime dateTime = formatter.parseDateTime(input);
return dateTime.toDate();
//printout shows: Thu Aug 15 17:00:48 EDT 2013
}
I know that the server is returning some crappy time format that is hard to work with (it took a while to get this to work in the iOS App we have, and even there it's still rather clunky) so I don't mind changing the webservice or the query if that would make things easier.
I have a very similar format, and I parse it using SimpleDateFormat, try this:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZZ", Locale.US);
Date dateTime = format .parse(value);
What i understand is that you have your correct instance of date already and what you need is to parse it to String.
I suggest you use:
DateFormat formatter = new SimpleDateFormat("d/MM/yyyy hh:mm:ss a");
//this will give you the format '8/15/2013 2:00:48 PM'
String d = formatter.format(date);
Hope this helps.
EDIT:
Also seams you want to have your date instance in -07:00 timezone
So you can change your line
DateTime dateTime = formatter.parseDateTime(input);
for
DateTime dateTime = formatter.withZone(DateTimeZone.forID("-07:00")).parseDateTime(input);

Categories