Java Server and Client Time - java

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>

Related

Date.toString not showing local timezone

I have a webapp . I am trying to log the time at which certain process got completed.
m_jobResults.addMessage("sum done", new Date().toString());
I am seeing that Date.toString() returns time in GMT as opposed to local timezone . If I write a test java program on same machine , it displays time in my local timezone. Could anyone suggest what is going wrong here.
Also note java.util.Calendar.getInstance().getTimeZone() shows gmt while debugging in webapp where as a sample test code shows as correct local timezone .
First you have to know is:
Date is always UTC-based.
Date does not have a "local instance."
If you want to have a to have a local time zone, use Date with Calendar and/or TimeZone.getDefault().
Use TimeZone.getTimeZone("Europe/Madrid") to get the Barcelona time zone.
If you want to find your server timezone check here:
final TimeZone timeZone = TimeZone.getDefault();
But maybe your server is not located where your user is... so to get user's locale with your server's timezone:
private String getServerTimeZoneDisplayName()
{
final TimeZone timeZone = TimeZone.getDefault();
final boolean daylight = timeZone.inDaylightTime(new Date());
final Locale locale = servletRequest.getLocale();
return timeZone.getDisplayName(daylight, TimeZone.LONG, locale);
}
If you convert a Date to a String directly, as you are doing by calling toString() on it, it will be formatted with the default timezone of the system that the code is running on. This happens to be GMT in your case.
If you want it to be formatted using a different timezone, then use a SimpleDateFormat object and specify the timezone you want on that object:
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
df.setTimeZone(TimeZone.getTimeZone("Europe/Berlin"));
String text = df.format(new Date());
System.out.println("The date and time: " + text);

how to convert UTC time to some other time zone ("CST","IST")

In my Android application server will return some UTC date in following format(yyyy-MM-dd HH:mm:ss) 24hours and I need to convert those time into user's TimeZone for example CST, IST.
I did the following code but I do know is it correct or not, please assist me to do the time zone conversion in right way.
I get UTC date as json string and converting into user's time zone format and showing Android side
private static Date utcDate;
private static DateFormat expireFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
try {
expireFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
utcDate = expireFormat.parse("2014-04-01 10:32:00");
System.out.println(TimeZone.getDefault().getID());
expireFormat.setTimeZone(TimeZone.getTimeZone(TimeZone.getDefault().getID()));
System.out.println(expireFormat.format(utcDate));
} catch (ParseException e) {
e.printStackTrace();
}
output of the code:
Asia/Calcutta
2014-04-01 16:02:00
The overall approach is OK if a re-formatted String is really what you're trying to get.
There are some issues though
SimpleDateFormat is not a threadsafe class. Setting it to a static field inside a server is a problem!
Same as #1 regarding using a static field to hold the intermediate Date object.
Is "CST" China Standard Time? Central Standard Time (US or Australia)? Cuba Standard Time? Three letter abbreviations TimeZone are bad news in general. Try to use an Olson Name or Alias if at all possible.
Is this the server side or the android? If it's a server, you could probably benefit from the new Java 8 API for DateTime handling.

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);

Java XML RPC date iso 8601 with timezone

I am having a hard time trying to make a web service client work. It is a XML RPC specification. I am using Apache WS XML-RPC library, which I find full of holes that causes problem due to Serialization. I have to send a Date parameter for the library to add the tags , however the web service expects it with the TZ, that means adding -0500 at the end of the Date object. If I dont send it as Date Object, it wont add the tags and it will fail. And when trying to do this:
DateFormat df = new SimpleDateFormat("yyyyMMdd'T'HH:mm:ssZ");
String fecha = df.format(new Date());
Date date = new SimpleDateFormat("yyyyMMdd'T'HH:mm:ssZ").parse(fecha);
And using parameter date, and it always sends it as
<dateTime.iso8601>20130517T20:30:33</dateTime.iso8601>
Can't find a way for it to send it as Date object in the format above but with the -0500 at the end. Any help would be appreciated.

How can I get the current time in particular format, for a particular zone?

I want to get the current DateTime in a zone of my choice and in a particular format (eg HH-MM-SS, MM-DD-YY, MoMo-DD-YY-HH-MM-SS etc).
How can I do this, using JodaTime?
Given that you've already seen the user guide (which includes sections on time zones and formatting), it's not really clear where your confusion is. Some sample code to get you going:
DateTimeZone zone = DateTimeZone.forID("Europe/London");
DateTime currentTimeInLondon = new DateTime(zone);
DateTimeFormatter formatter = DateTimeFormat.forPattern("HH:mm:ss, MM-dd-yyyy");
String text = formatter.print(currentTimeInLondon); // e.g. 08:24:54, 09-26-2012
It would be worth you taking some time to analyze why you couldn't get to this code yourself, given the information in the user guide. Being able to work out how to use APIs is a very important skill as a software engineer - you mustn't expect to be spoonfed code all the time.
this may help you.
http://joda-time.sourceforge.net/userguide.html
Use following code to get time according to particular zone with format.
Locale locale = Locale.FRENCH;
// Format with a custom format
DateFormat formatter = new SimpleDateFormat("E, dd MMM yyyy", locale);
String s = formatter.format(new Date());
// mar., 29 sept. 2012
// Format with a default format
s = DateFormat.getDateInstance(DateFormat.MEDIUM, locale).format(new Date());
// 29 sept. 2012

Categories