Converting EDT time zone to GMT not working fine in java - java

I am using this code to parse this date. It must show new date as "2012-06-20 03:09:38" as EDT is -4GMT and my current location is GMT+5. But its not showing this it now showing as it is
private static void convertEDT_TO_GMT() {
try {
String s = "2012-06-20 18:09:38";
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
df.setTimeZone(TimeZone.getTimeZone("EDT"));
Date timestamp = null;
timestamp = df.parse(s);
df.setTimeZone(TimeZone.getTimeZone("GMT+05:00"));
System.out.println("Old = " + s);
String parsed = df.format(timestamp);
System.out.println("New = " + parsed);
} catch (Exception e) {
e.printStackTrace();
}
}
It show
Old = 2012-06-20 18:09:38
New = 2012-06-20 23:09:38

The time zone 'EDT' does not exist. Doing a System.out.println() of `TimeZone.getTimeZone("EDT") shows that it is falling back to GMT because Java does not know 'EDT' as a time zone.
Changing from "EDT" to "GMT-04:00" gives the correct result:
try {
String s = "2012-06-20 18:09:38";
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//df.setTimeZone(TimeZone.getTimeZone("EDT"));
df.setTimeZone(TimeZone.getTimeZone("GMT-04:00"));
Date timestamp = null;
timestamp = df.parse(s);
df.setTimeZone(TimeZone.getTimeZone("GMT+05:00"));
System.out.println("Old = " + s);
String parsed = df.format(timestamp);
System.out.println("New = " + parsed);
} catch (Exception e) {
e.printStackTrace();
}
Result:
Old = 2012-06-20 18:09:38
New = 2012-06-21 03:09:38
According to this post:
Eastern Daylight Time isn't the name of a "full" time zone - it's "half" a time zone, effectively, always 4 hours behind UTC.
So using "GMT-04:00" might be the right solution.

TimeZone.setDefault(TimeZone.getTimeZone("GMT-04:00"));
Date date = new Date();
System.out.println("Current EDT Time is : "+date);

Related

How to print date in GMT format? [duplicate]

I have a string "2014-07-02T17:12:36.488-01:00" which shows the Mountain time zone. I parsed this into java.util.date format. Now I need to convert this to GMT format. Can anyone help me??
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Object dd = null;
try {
dd=sdf.parseObject("2014-07-02T17:12:36.488-01:00");
System.out.println(dd);
} catch (ParseException e) {
e.printStackTrace();`enter code here`
}
SimpleDateFormat gmtDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
gmtDateFormat.setTimeZone(java.util.TimeZone.getTimeZone("GMT"));
System.out.println("Current Date and Time in GMT time zone:+ gmtDateFormat.format(dd));
There are a few problems in your code. For example, the format string doesn't match the actual format of the string you are parsing.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");
Object dd = null;
try {
dd = sdf.parse("2014-07-02T17:12:36.488-01:00");
System.out.println(dd);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat gmtDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssX");
gmtDateFormat.setTimeZone(java.util.TimeZone.getTimeZone("GMT"));
System.out.println("Current Date and Time in GMT time zone:" + gmtDateFormat.format(dd));
To print the current date in whatever timezone you like, set the timezone you want to use on the SimpleDateFormat object. For example:
// Create a Date object set to the current date and time
Date now = new Date();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");
df.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println("Current date and time in GMT: " + df.format(now));
df.setTimeZone(TimeZone.getTimeZone("IST"));
System.out.println("Current date and time in IST: " + df.format(now));

Check between two datetime if passed in Java/Android

I have two date time string, one is current time and second is given as follows.
String currentTime = "05/30/2018 16:56:21";
String endTime = "05/30/2018 16:59:21";
Now I want to check if the endTime has passed currentTime.
Thanks
Take a look at
this and this
Example:
String currentTime = "05/30/2018 16:56:21";
String endTime = "05/30/2018 16:59:21";
SimpleDateFormat sdf = new SimpleDateFormat("dd/mm/yyyyHH:mm:ss");
try {
Date currentTimeDate = sdf.parse("05/30/2018 16:56:21");
Date endTimeDate = sdf.parse("05/30/2018 16:59:21");
currentTimeDate.compareTo(endTimeDate); // false / current time has not passed end time.
endTimeDate.compareTo(currentTimeDate); // true / end time has passed current time.
} catch (ParseException ignored) {
}
Convert both strings to Date object and then use before() method to check if the end time has passed currentTime.
String currentTime = "05/30/2018 16:56:21";
String endTime = "05/30/2018 16:59:21";
Date current=new SimpleDateFormat("dd/MM/yyyy").parse(currentTime);
Date end=new SimpleDateFormat("dd/MM/yyyy").parse(endTime);
if(end.before(current)) {
// end time has passed currenctTime
} else {
// no
}
Keep both times in milliseconds which is a long value
long currentTime= System.currentTimeMillis();
You can also convert your and time in millies using below code.
String givenDateString = "Tue Apr 23 16:08:28 GMT+05:30 2013";
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
try {
Date mDate = sdf.parse(givenDateString);
long endTime= mDate.getTime();
System.out.println("Date in milli :: " + endTime);
} catch (ParseException e) {
e.printStackTrace();
}
Now compare, if current time is larger then end time, thus current time has passed end time like below.
if(currentTime>endTime){
//Do stuff
}
Enjoy..

Date changing from one format to another format

I am trying to parse the date from one format to another format, but getting the parse exception. Please help me out on this issue.
String Orgdate= "2016-11-14T11:12:13";
java.util.Date tardate = null;
SimpleDateFormat dateFormat2 = new SimpleDateFormat("dd/mm/yyyy HH24:MI:SS");//Exception is in this line.
try {
targetdateformat = dateFormat2.parse(Orgdate);
} catch (ParseException e) {
e.printStackTrace();
}
Above code giving me date but different format,i am looking for date like below mention.
('14/11/2016 11:12:13')
Time format is 24 Hrs.
why not just do a simple hardcode to get the format you would like. For example...
String date = "2016-11-14T11:12:13";
String newDate = date.charAt(8) + "" + date.charAt(9) + "/" +
date.charAt(5) + "" + date.charAt(6) + "/" +
date.substring(0, 4) + " " + date.substring(11, 19);
System.out.println(newDate);
You need to parse to Date then format the date string to convert it into another format
String Orgdate= "2016-11-14T11:12:13";
java.util.Date tardate = null;
SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
try {
tardate = dateFormat2.parse(Orgdate);
System.out.println(tardate); // Mon Nov 14 11:12:13 UTC 2016
} catch (ParseException e) {
e.printStackTrace();
}
String formatted = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(tardate);
System.out.println(formatted); 14/11/2016 11:12:13
If you are using Java8 you can try below
LocalDateTime dateTime = LocalDateTime.parse("2016-11-14T11:12:13", DateTimeFormatter.ISO_LOCAL_DATE_TIME);
String formattedDate = dateTime.format(DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss")); // 14/11/2016 11:12:13
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date a = sdf.parse("2016-08-12T08:29:47");
sdf.applyPattern("dd/MM/yyyy HH:mm:ss");
System.out.println(sdf.toPattern()); // to see if new pattern applied
System.out.println(sdf.format(a)); // get output in desired format

Android Time UTC

I am working on an Android app that frequently travels from Time Zone to TZ. I am getting various errors with times and TZs. The latest error is, when I load the flat file with times (see below), everything looks good. When I save the app environment (aka all variables/objects to sharedprefs), stop and then restart the app the time displayed is no longer local but UTC.
I began developing the app just using the default/local TZ. However, this became very complicated with DST and various TZs. Therefore my current approach is to store time in the app in UTC, and calculate differences between UTC times as needed. Then convert the UTC-stored time to the local TZ on-demand for user interaction.
I recognize there are many posts related to android time. I think I have read most if not all on java.util.date and Joda. However, I am still stuck. So, here goes...
I have 3 sources of time for the app. 1) I read in UTC Strings from a flat file 2) I get milliseconds since the Epoch for system time stamp (in UTC). 3) I get UTC in a string via a rest API. The app does numerous calculations between the 3 categories such as time difference, add time, etc. Below I will post my code for each of these
1 - Convert string UTCs that come from a file
public static Date string2date(String strformat, String strdate){
Date tdate = timestamp();
TimeZone tz = TimeZone.getDefault() ;
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
SimpleDateFormat formatter = new SimpleDateFormat(strformat);
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
String dateInString = strdate;
try {
tdate = formatter.parse(dateInString);
} catch (ParseException e) {
e.printStackTrace();
}
return tdate;
}
2 - Get milliseconds since Epoch
public static Date timestamp() {
Calendar localCalendar = Calendar.getInstance(TimeZone.getDefault());
//Date currentTime = localCalendar.getTime();
Date currentTime = GetUTCdatetimeAsDate();
return currentTime;
public static Date GetUTCdatetimeAsDate()
{
//note: doesn't check for null
return StringDateToDate(GetUTCdatetimeAsString());
}
public static String GetUTCdatetimeAsString()
{
final SimpleDateFormat sdf = new SimpleDateFormat(longdt);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
final String utcTime = sdf.format(new Date());
return utcTime;
}
public static Date StringDateToDate(String StrDate)
{
Date dateToReturn = null;
SimpleDateFormat dateFormat = new SimpleDateFormat(longdt);
try
{
dateToReturn = (Date)dateFormat.parse(StrDate);
}
catch (ParseException e)
{
e.printStackTrace();
}
return dateToReturn;
}
3 - Get UTC in a string via a rest API (Format is "2017-02-10T01:09:00Z")
try {
Calendar tempCal = ISO8601.toCalendar(dateLocal);
Log.e (" fbu "," fsutc " + tempCal.getTime() );
ISODepDate = tempCal.getTime();
tempCal = ISO8601.toCalendar(dateLocal2);
ISOArrDate = tempCal.getTime();
//ab.setTimeZone(PST);
Log.e (" fbu "," fsutc " + dateLocal + " / " + dateLocal2);
Log.e (" fbu "," fsutc " + ISODepDate + " / " + ISOArrDate);
}
catch (Exception a){
int aa = 1;
Log.e (" exception "," a " + a);
}
public static Calendar toCalendar(final String iso8601string)
throws ParseException {
Calendar calendar = GregorianCalendar.getInstance();
TimeZone tz = TimeZone.getDefault() ;
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
String s = iso8601string.replace(".000Z", "+00:00");
try {
s = s.substring(0, 22) + s.substring(23); // to get rid of the ":"
} catch (IndexOutOfBoundsException e) {
throw new ParseException("Invalid length", 0);
}
Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").parse(s);
calendar.setTime(date);
return calendar;
}
4 - Finally, here is what I am using to "Display" the above 3 time categories in local time.
public String UTCtoLocal(Date indate, Boolean formatLong) {
Date utcDate = indate;
String result;
//Log.e( " utc "," indate " + indate);
/*utcDate = your own initialization here;*/
Date localDate = new Date(utcDate.getTime() + TimeZone.getDefault().getRawOffset());
//Log.e( " utc "," localdate " + localDate);
if (formatLong){
result = longd.format(localDate);
} else {
result = shortt.format(localDate);
}
return result;
The questions are, given the expectation that I store in UTC and display in Local, a) Have I implemented items 1-4 correctly? b) Will the above code actually store the times in UTC and display in local?
After flat file load everything looks good. After restart the times are displayed in UTC vs Local.

determine if current time in java is past a predetermined time by 15mins

I would like to determine when the current time equals a defined time + 15mins.
The defined time here is in the format:
private Date fajr_begins;
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm");
fajr_begins = new Time(formatter.parse(prayerTimes.get(0)).getTime());
The code I have come up so far, which is not working is (the code below is crappy I know
DateTime today = new DateTime();
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm");
now1 = new Time(formatter.parse(today));
Duration duration = new Duration(sunrise, now1);
System.out.println(" time to duha " + duration);
The context of the question is a little light. Do you want to use a thread, do you want to be alerted...?
However, as a basic example you could do something like...
// The time we want the alert...
String time = "16:00";
// The date String of now...
String date = new SimpleDateFormat("dd/MM/yyyy").format(new Date());
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");
try {
// The date + time to give us context
Date timeAt = sdf.parse(date + " " + time);
boolean rollOver = false;
// Determine if the time has already passed, if it has
// we need to roll the date to the next day...
if (timeAt.before(new Date())) {
rollOver = true;
}
// A Calendar with which we can manipulate the date/time
Calendar cal = Calendar.getInstance();
cal.setTime(timeAt);
// Skip 15 minutes in advance
cal.add(Calendar.MINUTE, 15);
// Do we need to roll over the time...
if (rollOver) {
cal.add(Calendar.DATE, 1);
}
// The date the alert should be raised
Date alertTime = cal.getTime();
System.out.println("Raise alert at " + alertTime);
// The timer with which we will wait for the alert...
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
System.out.println("duha");
}
}, alertTime);
} catch (ParseException ex) {
}
Now, before you complain about the Date, everything is relative. Without the Date part of the time, it's difficult to know when we should raise our alert. The Date just helps us pinpoint the when the alert should be raised...
Additional
Context is everything, for example...if we use the following...
String time = "16:00";
try {
Date timeAt = new SimpleDateFormat("HH:mm").parse(time);
System.out.println(timeAt);
} catch (ParseException ex) {
ex.printStackTrace();
}
The timeAt value be Thu Jan 01 16:00:00 EST 1970, which is really useless, the time will always be before now...
If, instead, we use something like...
String time = "16:00";
String date = new SimpleDateFormat("dd/MM/yyyy").format(new Date());
try {
Date timeAt = new SimpleDateFormat("dd/MM/yyyy HH:mm").parse(date + " " + time);
System.out.println(timeAt);
} catch (ParseException ex) {
ex.printStackTrace();
}
The timeAt will now be Thu Sep 05 16:00:00 EST 2013 which gives us some context to now
Now if we use Calendar to advance the time by 15 minutes...
Calendar cal = Calendar.getInstance();
cal.setTime(timeAt);
cal.add(Calendar.MINUTE, 15);
Date checkTime = cal.getTime();
System.out.println(checkTime);
The checkTime becomes Thu Sep 05 16:15:00 EST 2013. I use Calendar because it will automatically roll the hour and date for me should it need to be...
This now allows us to start using the default available API functionality. Because it's highly unlikely that the milliseconds will ever match, I would be temtered to do something like...
Calendar watchFor = Calendar.getInstance();
watchFor.setTime(timeAt);
watchFor.set(Calendar.MILLISECOND, 0);
watchFor.set(Calendar.SECOND, 0);
Calendar now = Calendar.getInstance();
now.setTime(new Date());
now.set(Calendar.MILLISECOND, 0);
now.set(Calendar.SECOND, 0);
if (watchFor.equals(now)) {
System.out.println("Go for it...");
}
Zeroing out the milliseconds and seconds, so I can compare the Date and time (HH:mm) alone.
You could of course compare the milliseconds directly as well...
Is this you want to do? Following sentence I got in that way.
I would like to determine when the current time equals a defined time + 15mins.
you can simply do as follows
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm");
Date preDefineTime=formatter.parse("10:00");
long additionMin=15*60*1000;
System.out.println(formatter.format(preDefineTime.getTime()+additionMin));

Categories

Resources