format as GMT/UTC time when default timezone is something else - java

I have a program which needs to run under my local timezone for other reasons, but for one procedure i need to output dates using a SimpleDateFormat in GMT.
what is the tidiest way to do this?

Using the standard API:
Instant now = Instant.now();
String result = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG)
.withZone(ZoneId.of("GMT"))
.format(now);
System.out.println(result);
The new DateTimeFormatter instances are immutable and can be used as static variables.
Using the old standard API:
TimeZone gmt = TimeZone.getTimeZone("GMT");
DateFormat formatter = DateFormat.getTimeInstance(DateFormat.LONG);
formatter.setTimeZone(gmt);
System.out.println(formatter.format(new Date()));

Given that SimpleDateFormat isn't thread-safe, I'd say that the tidiest way is to use Joda Time instead. Then you can create a single formatter (calling withZone(DateTimeZones.UTC) to specify that you want UTC) and you're away:
private static DateTimeFormatter formatter = DateTimeFormat.forPattern(...)
.withZone(DateTimeZone.UTC);
...
String result = formatter.print(instant);
This has the other benefit that you can use Joda Time elsewhere in your code, which is always a good thing :)

Related

Format a String to a Fixed Date at UTC+0 in Java

I want to convert a String date - 2017-01-01 to java.util.Date with UTC+0. So, what I am expecting is.
"2017-01-01" -> 2017-01-01T00:00:00 UTC+0100
Here is how I am trying to do, but as my default Timezone is UTC+1, I am getting that 1 hour added to the Date.
Date d = Date.from(Instant.parse("2017-01-01T00:00:00Z"));
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss 'UTC'ZZZZZ");
String output = sf.format(d);
System.out.println(output);
Here is the output:
2017-01-01T01:00:00 UTC+0100
Can somebody help?
Your code is mixing oldfashioned and modern classes. Date and SimpleDateFormat are long outdated. Instant is modern (from 2014). I recommend you stick to the modern ones unless you are working with an old API that requires and/or gives you an instance of an oldfashioned class. So the answer is
String output = LocalDate.parse("2017-01-01")
.atStartOfDay(ZoneOffset.ofHours(1))
.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss 'UTC'XX"));
The result is the one you asked for
2017-01-01T00:00:00 UTC+0100
The code is not really shorter than yours, but once you get used to the fluent style you will find it clearer and more natural. The room for confusion and errors is considerably reduced.
If you want the start of day in whatever time zone the user is in, just fill in ZoneId.systemDefault() instead of ZoneOffset.ofHours(1).
LocalDate parses your date string — "2017-01-01" — without an explicit format. The string conforms to ISO 8601, and the modern classes use this standard as their default for parsing and also for their toString().
You can set the timezone first and then format it.
sf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = sf.parse(d);
And now format as per your requirements:
String output = sf.format(date);
System.out.println(output);
I wonder please try this also:
Date date = new Date();
TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
Calendar cal = Calendar.getInstance(TimeZone.getDefault());
date = cal.getTime();

Java Types: What is the format for representing a variable of type `Date`? `Time`?

I have a varaibles:
Date date;
Time time;
and methods:
MyDateMethod(Date date){
//do stuff
}
MyTimeMethod(Time time){
//do stuff
}
I tried using MyDateMethod() with the following call:
MyDateMethod(1995-03-7);
I get an error saying I've supplied it with type int when it expected type Time.
I also tried using MyTimeMethod() with the following call:
MyTimeMethod(03:04:55);
I get an error saying Type mismatch: Cannot convert type int to boolean.
What is the format to put in a variable of these different types? Date is obviously not xxxx-xx-xx and Time is obviously not xx:xx:xx.
There are a few options,
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
Date d = sdf.parse("1995-03-07");
System.out.println(d);
} catch (ParseException e) {
e.printStackTrace();
}
Output is
Tue Mar 07 00:00:00 EST 1995
Or, you could use
// -1 because January is 0... I didn't design it!
Calendar c = new GregorianCalendar(1995, 3 - 1, 7);
System.out.println(c.getTime());
with the same output as before.
SimpleDateFormat is what You need. It's need to be initialized by format of date.
Use it like this:
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy/MM/dd HH:mm:ss", Locale.getDefault());
and then:
Date date = (Date) dateFormat.parse("2014/04/02 22:22:22");
Take a look at DateFormat and particularly SimpleDateFormat.
Your example would be coded like this, using SimpleDateFormat:
Date date = new SimpleDateFormat("yyyy-MM-dd").parse("1995-03-07")
(I'm assuming you have months before days here, you will need to interchange the MM and dd if not).
Java does not support Date literals. You need to use a constructor or a static factory method to obtain an instance of this class.
1995-03-07 returns 1985 because you have three int literals here and the hyphens are interpreted as subtraction operators.
Take a look at the documentation for the Date class and the DateFormat class
Here's a way you could represent these values:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = dateFormat.parse("1995-03-07");
SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
Date time = timeFormat.parse("03:46:16");
You can use the same format objects to perform the reverse of this conversion. Please mind that these Date instances represent a specific moment in time, down to millisecond level. Internally, this is represented as the number of milliseconds since January 1, 1970, 00:00:00 GMT
This API is hardly the prettiest one in Java and by looking at the docs you can see how many changes it has undergone. Just look at the number of deprecated methods.
I recommend taking a look at the Joda-Time library instead.
Alternatively, if using Java 8 is an option for you, you can try the brand new API that comes with it
The answer by Tom is correct. No date-time literals inJava.
And as he stated, the old bundled java.util.Date and .Calendar classes are notoriously troublesome. Avoid them. Use either the Joda-Time library or the new java.time package in Java 8.
Joda-Time
In Joda-Time:
If you want only a date without time and time zone, use the LocalDate class.
Similarly to use only time while ignoring time zone and date, use the LocalTime class.
But most often you'll probably want to use the DateTime class which tracks date, time, and time zone all in one object.
A Date-Time Is Not Text
A DateTime object does not contain text. No String. If you need a string representation, use a formatter object to generate one. Search StackOverflow for many examples.
Built into Joda-Time are formatters for the sensible and increasingly common ISO 8601 standard. For example, the toString implementation on the DateTime class produces a String like this…
2014-04-01T20:17:35-08:00

different results for SimpleDateFormat in local and live environments

I have the following code
public String getDate(Date date) throws Exception{
String finalDate = "";
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
finalDate = formatter.format(date);
return finalDate;
}
I passed the input for this method as 9999-12-30 18:30:00.0.
In my live environment the result is :12/30/9999
In my local environment the result is :12/31/9999
What might be the reason for this strange behaviour. Thanks in advance..
Because there is a timezone difference between your live environment and local
To force your dateformat to use a specific time zone, for example UTC, you can use:
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
Time zone format for sure. I would recommend you instead of using SimpleDateFormat use JodaTime.
Also if you want prevent time zone problem for all environments formatter.setTimeZone("UTC")
#psr as you mentioned that your local server is in India and production is in US.
The timezone is the issue so it is creating this problem.
Since your production server is in US, try this.
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
One good thing to keep in mind is that java.util.Date does not have a notion of time zone in it. I'm always surprised how few people know that. So if you want unified results in your application, make sure you use timezone when you parse and when you print.
As #assylias said, you can set timezone of date formatter to achieve this.

How do I convert timestamp string to local time string?

I have timestamp string: "1989-01-01 00:00:00" and i need convert it to local date format.
I execute:
SimpleDateFormat TIMESTAMPFORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
DateFormat.getDateFormat(getContext()).format(TIMESTAMPFORMAT.parse("1989-01-01 00:00:00"));
And getDateFormat returns 31.12.1988
Why?
How can I receive 01.01.1989???
In order to skip time-zone when formatting, I would suggest you to set it to default as below:
SimpleDateFormat TIMESTAMPFORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
TIMESTAMPFORMAT.setTimeZone(TimeZone.getTimeZone("GMT"));
This is probably to do with the time zones involved. I strongly suspect that you're formatting in a different time zone to the one you're using for parsing, and the value goes to before midnight, basically. If you can use the same time zone on both, it's likely to work.
If you possibly can, I'd encourage you to use Joda Time instead though - you really want a LocalDate.

Code to convert seconds to Date and time combination in java

I have seconds like below:
1320130800
I need to convert the value into Date and Time Combination format. While formatting I got the result as follows:
Tuesday,November 1,2011 2:00,AM
But the correct result is as follows:
Tuesday,November 1,2011 7:00,AM
For the above format conversion I used the below code:
long millis = 1320130800*1000;
Date date = new Date(millis);
SimpleDateFormat sdf = new SimpleDateFormat("EEEE,MMMM d,yyyy h:mm a");
String formattedDate = sdf.format(date);
System.out.println(formattedDate);
Can any one guide me to get the correct answer?
Sounds like it's just a time zone issue - you need to set the time zone for the formatter:
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
(Note that in your sample code, long millis = 1320130800*1000; doesn't work as it performs the multiplication in 32-bit arithmetic; you need something like long millis = 1320130800L*1000;.)
Use the Calendar API instead.
After you have the Date object, construct a Calendar object (getInstance() returns one with the default Time Zone) and do setDate(Date) on it and parse it like that.
Alternatively, you can take a look at Joda Time APIs since they are easy to use.
Regards!

Categories