getting the wrong timezone in java / android [duplicate] - java

This question already has answers here:
Is java.util.Date using TimeZone?
(5 answers)
Closed 7 years ago.
String = 26/8/2013 15:59;
I want to convert this date into GMT, however after applying the below code, I get the EEST time rather than the GMT.
DateFormat df = new SimpleDateFormat("dd/MM/yyyy h:m");
df.setTimeZone(TimeZone.getTimeZone("UTC"));
df.parse(newDate);
Log.i(tag, df.parse(newDate).toString());
Output :
Mon Aug 26 18:59:00 EEST 2013
Whats wrong ?

Your parsing is correct, the different is just for your locale time zone that is used to display when you are making toString(). I just used formatted output to demonstrate the correct format . Here is the details example:
final String time = "26/8/2013 15:59";
TimeZone timeZone = TimeZone.getTimeZone("UTC");
final String REQUEST_DATE_FORMAT = "dd/MM/yyyy h:m";
DateFormat format = new SimpleDateFormat(REQUEST_DATE_FORMAT);
Date localDate = format.parse(time);
// localDate.toString()
// PRINT. Mon Aug 26 15:59:00 EEST 2013
Calendar cal = Calendar.getInstance(timeZone);
cal.setTime(localDate);
format.setTimeZone(timeZone);
final String utcTime = format.format(cal.getTime());
// PRINT. 26/08/2013 12:59

Nothing's really wrong. You are successfully parsing the datetime string interpreted as UTC timezone.
When printing it to log, you get what you ask for - Date.toString() returns the date formatted to current locale settings which include the timezone. The difference between UTC and EEST is 3 hours.
If you want to to format it to display some other timezone, pass it though format() of a SimpleDateFormat that is configured to the timezone you want.

I think you should use the below approach:
Date myDate = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
calendar.setTime(myDate);
Date time = calendar.getTime();
SimpleDateFormat outputFmt = new SimpleDateFormat("MMM dd, yyy h:mm a zz");
String dateAsString = outputFmt.format(time);
System.out.println(dateAsString);

Related

Using SimpleDateFormat to format a string parse exception? [duplicate]

This question already has answers here:
String to Date Conversion mm/dd/yy to YYYY-MM-DD in java [duplicate]
(5 answers)
Closed 4 years ago.
I have a date object that returns the below string value in doing date.toString()
String date = "Wed Jun 27 12:33:00 CDT 2018";
And I want to format it in exactly this style:
"June-27-2018 5:33:00 PM GMT".
I tried using SimpleDateFormat
protected SimpleDateFormat dateFormat = new SimpleDateFormat( "MMMM-dd-yyyy h:mm:ss a z", Locale.US);
But I keep getting a parse exception. Is there any way to format this the way I need it to? The timezone needs to be converted too.
First, you shouldn’t have a Date object. The Date class is long outdated (no pun intended). Today you should prefer to use java.time, the modern and much nicer date and time API. However, I am assuming that you are getting a Date from some legacy API that you cannot change. The first thing you should do is convert it to an Instant. Instant is the corresponding class in java.time. Then you should do any further operations from there.
DateTimeFormatter formatter
= DateTimeFormatter.ofPattern("MMMM-dd-yyyy h:mm:ss a z", Locale.US);
ZoneId desireedZone = ZoneId.of("Etc/GMT");
Date yourOldfashionedDate = // …;
ZonedDateTime dateTimeInGmt = yourOldfashionedDate.toInstant().atZone(desireedZone);
String formattedDateTime = dateTimeInGmt.format(formatter);
System.out.println(formattedDateTime);
This snippet prints the desired:
June-27-2018 5:33:00 PM GMT
Converting directly from the Date object is safer and easier than converting from its string representation. The biggest problem with the latter is that the string contains CDT as time zone, which is ambiguous. It may stand for Australian Central Daylight Time, North American Central Daylight Time, Cuba Daylight Time or Chatham Daylight Time. You cannot be sure which one Java is giving you. Never rely on three and four letter time zone abbreviations if there is any way you can avoid it.
Link: Oracle tutorial: Date Time explaining how to use java.time.
Your date string cannot parse to the format you have given, so change the format to EEE MMM dd HH:mm:ss zzz yyyy
String myDate = "Wed Jun 27 12:33:00 CDT 2018";
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
SimpleDateFormat dateFormat_2 = new SimpleDateFormat("MMMM-dd-yyyy h:mm:ss a z", Locale.US);
dateFormat_2.setTimeZone(TimeZone.getTimeZone("GMT"));
Date d = dateFormat.parse(myDate);
dateFormat_2.format(d);
System.out.println(dateFormat_2.format(d));
Output :
June-27-2018 12:33:00 PM GMT
You will achieve your desired output if you pass date or object to format function.
SimpleDateFormat dateFormat = new SimpleDateFormat( "MMMM-dd-yyyy h:mm:ss a z", Locale.US);
String ans=dateFormat.format(param);
In above code param must be date or object so first convert string to date and then apply format function to get your desired output.
See below Sample code
SimpleDateFormat dateFormat = new SimpleDateFormat( "MMMM-dd-yyyy h:mm:ss a z", Locale.US);
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
String ans=dateFormat.format(new Date());
Sample output:
June-27-2018 6:22:35 PM GMT

How can I get expected Date format in my DAO class

I've got Timestamp format in DB and my setEventDate method needs Date format.
So in my DAO class there is something like this :
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
Timestamp dbDate = rows.getTimestamp("event_date");
String dbDateToString = new SimpleDateFormat("HH:mm").format(dbDate);
Date dbDateToDate = sdf.parse(dbDateToString);
e.setEventDate(dbDateToDate);
System.out.println(dbDateToString);
System.out.println(dbDateToDate);
I'm getting Timestamp from DB, format it to String and in next step I'm parsing it to Date. I know that it sounds weird. The result is:
String - 17:08
Date - Thu Jan 01 17:08:00 CET 1970
I don't get it :/ I need that "HH:mm" format.
You are taking a Timestamp from your DB, you need to change it a Date first
Timestamp dbDate = rows.getTimestamp("event_date");
Date d = new Date(dbDate.getTime();
now you can do your SimpleDateFormat formatting stuff
Timestamp dbDate = rows.getTimestamp("event_date");
Date d = new Date(dbDate.getTime());
String dbDateOnlyHourAndMinutes = new SimpleDateFormat("HH:mm").format(dbDate);
there you have your Hour and minutes only "Date".
You say you want to parse date but in your date format you are passing only hours (HH) and minutes (mm) format.
Check how to create your desired date format from :
What are the date formats available in SimpleDateFormat class?
https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
example of a date format is: dd/MM/yyyy.
In case i did not understood correctly please explain more.
Here is an example code to convert the timestamp to your format.
ASSUMPTION: desired date format is MM:yyyy:
Timestamp stamp = new Timestamp(System.currentTimeMillis());//your timestamp goes here
Date date = new Date(stamp.getTime());
System.out.println(date);//result = Tue Mar 27 18:50:09 EEST 2018
SimpleDateFormat sdf = new SimpleDateFormat("MM:yyyy");
System.out.println(sdf.format(date)); //result = 03:2018

JAVA : how to add extra time for timestamp [duplicate]

This question already has answers here:
How can I increment a date by one day in Java?
(32 answers)
Closed 8 years ago.
Sorry im new to java, may i know how can i add extra time in here?
SimpleDateFormat timestampFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
String currTimestamp = timestampFormat.format(new Date());
System.err.println("currTimestamp=="+currTimestamp); // 2014/10/17 14:31:33
You can use Calender for this.
Calendar calendar=Calendar.getInstance(); // current time
System.out.println(calendar.getTime());
calendar.add(Calendar.MINUTE,3); // add 3 minutes to current time
System.out.println(calendar.getTime());
Out put:
Fri Oct 17 12:17:13 IST 2014
Fri Oct 17 12:20:13 IST 2014
Just as a comparison, using Java 8's new time API...
LocalDateTime ldt = LocalDateTime.now();
System.out.println(ldt.format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG)));
ldt = ldt.plusMinutes(3);
System.out.println(ldt.format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG)));
Or if you can't use Java 8, you could use the JodaTime API
SimpleDateFormat timestampFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
DateTime dt = DateTime.now();
System.out.println(timestampFormat.format(dt.toDate()));
dt = dt.plusMinutes(3);
Date date = dt.toDate();
System.out.println(timestampFormat.format(dt.toDate()));
Calander class have some useful methods to do this. If you want to still use Date it self, Add 3000 milliseconds to the current time.
String resultTime = timestampFormat.format(new Date(new Date().getTime() + 3000));
It would be better to use the Calendar class instead of using deprecated Date class:
Pull a Calendar instance:
Calendar c = Calendar.getInstance();
Add 3 minutes to the calendar current time:
c.add(Calendar.MINUTE, 3);
Format the new calendar time:
SimpleDateFormat timestampFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
String currTimestamp = timestampFormat.format(c.getTime());
System.err.println("currTimestamp==" + currTimestamp);

Getting UTC time with Calendar and Date [duplicate]

This question already has answers here:
Calendar.getInstance(TimeZone.getTimeZone("UTC")) is not returning UTC time
(7 answers)
Closed 8 years ago.
I'm trying to get an instance of Date with UTC time using the following code:
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
Date now = cal.getTime();
that looks so simple, but if I check the values at IntelliJ's debugger, I get different dates for cal and now:
cal:java.util.GregorianCalendar[time=1405690214219,areFieldsSet=true,lenient=true,zone=GMT,firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=2014,MONTH=6,WEEK_OF_YEAR=29,WEEK_OF_MONTH=3,DAY_OF_MONTH=18,DAY_OF_YEAR=199,DAY_OF_WEEK=6,DAY_OF_WEEK_IN_MONTH=3,AM_PM=1,HOUR=1,HOUR_OF_DAY=13,MINUTE=30,SECOND=14,MILLISECOND=219,ZONE_OFFSET=0,DST_OFFSET=0]
now:Fri Jul 18 10:30:14 BRT 2014
as you can see, cal is 3 hours ahead of now... what am I doing wrong?
Thanks in advance.
[EDIT] Looks like TimeZone.setDefault(TimeZone.getTimeZone("UTC")); before the code above does the job...
This question has already been answered here
The System.out.println(cal_Two.getTime()) invocation returns a Date from getTime(). It is the Date which is getting converted to a string for println, and that conversion will use the default IST timezone in your case.
You'll need to explicitly use DateFormat.setTimeZone() to print the Date in the desired timezone.
TimeZone timeZone = TimeZone.getTimeZone("UTC");
Calendar calendar = Calendar.getInstance(timeZone);
SimpleDateFormat simpleDateFormat =
new SimpleDateFormat("EE MMM dd HH:mm:ss zzz yyyy", Locale.US);
simpleDateFormat.setTimeZone(timeZone);
System.out.println("Time zone: " + timeZone.getID());
System.out.println("default time zone: " + TimeZone.getDefault().getID());
System.out.println();
System.out.println("UTC: " + simpleDateFormat.format(calendar.getTime()));
System.out.println("Default: " + calendar.getTime());
Edit To convert cal to date
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DATE);
System.out.println(year);
Date date = new Date(year - 1900, month, day); // is same as date = new Date();
Just build the Date object using the Cal values. Please let me know if that helps.
Try using a date formatter and set the time zone to UTC.
dateFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));

Date converter in JAVA [duplicate]

This question already has answers here:
How to parse a date? [duplicate]
(5 answers)
Closed 9 years ago.
I have date like Tue Mar 19 00:41:00 GMT 2013, how to convert it to 2013-03-19 06:13:00?
final DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
final Date date = bdate;
Date ndate = formatter.parse(formatter.format(date));
System.out.println(ndate);
gives the same date.
Use two SimpleDateFormat objects with appropriate formats and use the first to parse the string into a date and the second to format the date into a string again.
As the first answer says. First parse your date with SimpleDateFormat like this:
Date from = new SimpleDateFormat("E M d hh:mm:ss z yyyy").parse("Tue Mar 19 00:41:00 GMT 2013");
Then use that to format the resulting date object with another instance of SimpleDateFormat like this:
String to = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(from);
See the javadoc of SimpleDateFormat here. Hope that helps.
One major thing that the others have left out is dealing with the timezone (TZ). Anytime you use a SimpleDateFormat to go to/from a string representation of the date, you really need to be aware of what TZ you're dealing with. Unless you explicitly set the TZ on the SimpleDateFormat, it will use the default TZ when formatting/parsing. Unless you only deal with date strings in the default timezone, you'll run into problems.
Your input date is representing a date in GMT. Assuming that you also want the output to be formatted as GMT, you need to make sure to set the TZ on the SimpleDateFormat:
public static void main(String[] args) throws Exception
{
String inputDate = "Tue Mar 19 00:41:00 GMT 2013";
// Initialize with format of input
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
// Configure the TZ on the date formatter. Not sure why it doesn't get set
// automatically when parsing the date since the input includes the TZ name,
// but it doesn't. One of many reasons to use Joda instead
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
Date date = sdf.parse(inputDate);
// re-initialize the pattern with format of desired output. Alternatively,
// you could use a new SimpleDateFormat instance as long as you set the TZ
// correctly
sdf.applyPattern("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.format(date));
}
Use SimpleDateFormat in this way:
final DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
final Date date = new Date();
System.out.println(formatter.format(date));
If you do any calculations or parsing with dates please use JodaTime because the standard JAVA date support is really buggy

Categories

Resources