Calculating the time difference between two GMT time instances as String - java

I am trying to get time difference between dates as String format like 4 hours ago.
Here is my code
To my understanding Calendar.getInstance() gives time as GMT. my server time is GMT so the difference should be GMT Vs GMT however the difference with this code is GMT (Server) Vs. GMT +5 ( My Current timezone)
How can i make the difference GMT only?
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date convertedDate = new Date();
Calendar systemCal = Calendar.getInstance();
long currentTime = systemCal.getTimeInMillis();
/***********************************/
Calendar cal = Calendar.getInstance();
try {
convertedDate = dateFormat.parse(dateString);
} catch (Exception e) {
return "";
}
cal.setTime(convertedDate);
/***********************************/
CharSequence myDateString = DateUtils.getRelativeTimeSpanString(cal.getTimeInMillis(), currentTime, DateUtils.MINUTE_IN_MILLIS);
return myDateString.toString();

Try following codes. It demonstrates clearly on how to parse a String datetime to GMT timezone. Key point is the first line which sets the default timezone.
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
try {
Date convertedDate = dateFormatGmt.parse("2015-01-29 10:05:00");
long diffSeconds = (cal.getTimeInMillis() - convertedDate.getTime()) / 1000;
System.out.println("convertedDate: " + convertedDate);
System.out.println("current: " + cal.getTime());
System.out.println("Difference in seconds: " + diffSeconds);
}
catch (Exception e) {
e.printStackTrace();
}

The Calendar.getInstance() return the time zone the computer is set to. So unless you always have control over that i would advice using the getInstance(TimeZone zone) method.
http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#getInstance%28java.util.TimeZone%29
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
But if you want a easier way to do it i would advice to look in to joda time.
http://www.joda.org/joda-time/

Related

codenameone convert time to utc

I am working on codename one project and I am struggling to convert device time to UTC.
I use this code :
Calendar cal = Calendar.getInstance();
System.out.println(cal.getTimeZone());
TimeZone tzUTC = TimeZone.getTimeZone("UTC");
com.codename1.l10n.DateFormat dtfmt = new com.codename1.l10n.SimpleDateFormat("EEE, yyyy-MM-dd KK:mm a z");
dtfmt.setTimeZone(tzUTC);
System.out.println("UTC: " + dtfmt.format(cal.getTime()));
and codename one reject the setTImeZone method.
I use java.text.DateFormat but when I run it, condename one cant compile it also.
It may not really answer your real question, but the following works for me:
Calendar cal = Calendar.getInstance();
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG);
TimeZone tzUtc = TimeZone.getTimeZone("UTC");
df.setTimeZone(tzUtc);
System.out.println("UTC: " + df.format(cal.getTime()));
I don’t know com.codename1.l10n.DateFormat, so I’m sorry I cannot help you there.
Use:
java.util.Calendar cal = java.util.Calendar.getInstance();
TimeZone tz = cal.getTimeZone();
cal.setTime(new Date(System.currentTimeMillis() - tz.getRawOffset()));
com.codename1.l10n.DateFormat dtfmt = new com.codename1.l10n.SimpleDateFormat("EEE, yyyy-MM-dd KK:mm a");
System.out.println("UTC: " + dtfmt.format(cal.getTime()));
Then append UTC to the string as the value is always UTC.
Was using Shai's solution but noticed that it wasn't giving the correct UTC time when the device timezone was in daylight savings time. Below is a more general solution using tz.getOffset() instead of tz.getRawOffset(). Seems like there should be simpler way!
L10NManager l10n = L10NManager.getInstance();
long sysRtnTime = System.currentTimeMillis() / 1000L;
Date errorDate = new Date(sysRtnTime * 1000L);
Date currentDate = new Date();
String deviceTime = l10n.formatDateTime(errorDate);
Calendar c = Calendar.getInstance();
long unixtime = errorDate.getTime();
TimeZone tz = c.getTimeZone();
// to get offset, we need era, year, month, day, dayOfWeek,millis
SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy");
SimpleDateFormat monthDateFormat = new SimpleDateFormat("MM");
SimpleDateFormat dayDateFormat = new SimpleDateFormat("dd");
SimpleDateFormat dayOfWeekDateFormat = new SimpleDateFormat("F");
SimpleDateFormat millisDateFormat = new SimpleDateFormat("S");
int year = Integer.parseInt(yearFormat.format(currentDate));
int month = Integer.parseInt(monthDateFormat.format(currentDate));
int day = Integer.parseInt(dayDateFormat.format(currentDate));
int dayOfWeek = Integer.parseInt(dayOfWeekDateFormat.format(currentDate));
int millis = Integer.parseInt(millisDateFormat.format(currentDate));
// c.setTime(new Date(unixtime - tz.getRawOffset())); // c in UTC only if device not DST
month = month - 1; // since getOffset assume 0 = Jan and 11 = Dec
c.setTime(new Date(unixtime - tz.getOffset(1, year, month, day, dayOfWeek, millis))); // c in UTC (even if device in DST)
Date cDateUTC = c.getTime(); // sDate in UTC
String timeInUTC = serverDateFormat.format(cDateUTC);
Log.p("Time (in device timezone): " + deviceTime);
Log.p("Time (in UTC): " + timeInUTC);

How to parse "dd-MM" date format to get current year?"

I have to parse "17-Jun" format date using Java.But the problem is when I try to parse "dd-MM" format using SimpleDateFormat it is returning as "Wed Jun 17 00:00:00 IST 1970".Is it possible to get current(2014) year instead of 1970.
My result:
17/JUNE/1970
Expected result:
17/JUNE/2014
Have a look at this..
Calendar c = Calendar.getInstance();
c.set(Calendar.DATE, 17);
c.set(Calendar.MONTH, 5);
c.set(Calendar.YEAR, c.get(Calendar.YEAR));
Date date=new Date(c.getTimeInMillis());
SimpleDateFormat simpleDateformatter = new SimpleDateFormat("dd/mmm/yyyy");
String convertedDate = simpleDateformatter .format(date);
To get year you can just use
Calendar cal = Calendar.getInstance();
cal.get(Calendar.YEAR) will fetch you current year
Hope it helped... :)
Try this
Calendar c = Calendar.getInstance();
c.set(Calendar.DATE, 17);
c.set(Calendar.MONTH, 5);
c.set(Calendar.YEAR, c.get(Calendar.YEAR));
Date d=new Date(c.getTimeInMillis());
SimpleDateFormat formatter = new SimpleDateFormat("dd- mmm");
String conDate = formatter.format(d);
Do like this
Date date = new SimpleDateFormat("dd-MMM-yyyy").parse("17-Jun-"+ Calendar.getInstance().get(Calendar.YEAR));
You'll have to write a utility method, there isn't anything in SimpleDateFormat that will interpret a non-existant year as the current year. Something like this:
public static Date parseDate(String dateString) throws ParseException {
//determine current year
Calendar today = Calendar.getInstance();
int currentYear = today.get(Calendar.YEAR);
//parse input
SimpleDateFormat format = new SimpleDateFormat("dd-MMM");
Date parsed = format.parse(dateString);
// set current year on parsed value
Calendar cal = Calendar.getInstance();
cal.setTime(parsed);
cal.set(Calendar.YEAR, currentYear);
return cal.getTime();
}
Try this:
SimpleDateFormat dfDate = new SimpleDateFormat("dd-MM-yyyy");
java.util.Date d = null;
try {
d = dfDate.parse("17-Jun-"+ Calendar.getInstance().get(Calendar.YEAR));
} catch (java.text.ParseException e) {
e.printStackTrace();
}
System.out.println(""+d );
your problem will be solved.
java.time
In Java 8 you can do something like:
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("d-MMM");
MonthDay md = MonthDay.parse("17-Jun", dtf);
LocalDate d = LocalDate.now().with(md);
System.out.println(d.getDayOfMonth());
System.out.println(d.getMonthValue());
System.out.println(d.getYear());
I guess the simplest way is to do this:
DateFormat dateFormat = new SimpleDateFormat("yyyy/MMM/dd");
Date date = new Date();
System.out.println("Time is: " + dateFormat.format(date) );
This gives you exactly what you want. also see
http://docs.oracle.com/javase/tutorial/i18n/format/simpleDateFormat.html
Little late, but if you really don't want to use Calendar at all - as I gather from your comments to the correct answers above - (not recommended with the usage of deprecated methods, but still):
SimpleDateFormat format = new SimpleDateFormat("dd-MMM");
Date date = format.parse("17-JUN");
date.setYear(new Date().getYear());
System.out.println(date);
Output:
Tue Jun 17 00:00:00 IST 2014
All answers given here are more or less correct, but I notice that one detail aspect is still overlooked, namely if the combination of day and months fits to current year (february 29 problem). So I would suggest a strict parsing like following:
String ddMMM = "17-Jun";
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
sdf.setLenient(false); // in order to check for "29-Feb"
TimeZone tz = TimeZone.getDefault(); // or change to your specific time zone
Date date =
sdf.parse(ddMMM + "-" + new GregorianCalendar(tz).get(Calendar.YEAR));
Try,
String s2 = "Wed Jun 17 00:00:00 1970";
SimpleDateFormat sdf1 = new SimpleDateFormat("E MMM dd hh:mm:ss yyyy");
SimpleDateFormat sdf2 = new SimpleDateFormat("dd/MMM/yyyy");
try {
Date d1 = sdf1.parse(s2);
System.out.println(d1);
String s3 = sdf2.format(d1);
System.out.println("Before Changing :: "+s3);
Calendar cal = Calendar.getInstance();
cal.setTime(d1);
cal.add(Calendar.YEAR, 2014-1970);
d1 = cal.getTime();
String s4 = sdf2.format(d1);
System.out.println("After Changing :: "+s4);
} catch (ParseException e) {
e.printStackTrace();
}
Output
Before Changing :: 17/Jun/1970
After Changing :: 17/Jun/2014

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

Date / time changed to current server time in java calendar when adding seconds

I create a calendar object from a string date I receive.
Calendar cal = Calendar.getInstance();
String date = "example Mon, 22 Oct 2012 23:58:31 GMT";
SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
sdf.setTimeZone (TimeZone.getTimeZone ("PST"));
try {
cal.setTime(sdf.parse(date));
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println("date "+sdf.format(cal.getTime()));
This date converts and prints the gmt time to pst with no problem.
I then loop through an array of the elements object and add seconds
int offset = element.getSeconds;
cal.add(Calendar.SECOND, offset);
System.out.println("times cal offset: " + cal.getTime());
This cal now prints the server time (which is eastern time) and not the converted gmt that is printed above. Does something bypass the cal created from the string gmt date when seconds are added?
Thanks!
This because you don't use SDF with setted GMT timezone for printing in second time.

converting a date string into milliseconds in java [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Calculate date/time difference in java
how would a future date such as Sat Feb 17 2012 be converted into milliseconds in java that can then be subtracted from the current time in milliseconds to yield time remaining until that future date.
The simplest technique would be to use DateFormat:
String input = "Sat Feb 17 2012";
Date date = new SimpleDateFormat("EEE MMM dd yyyy", Locale.ENGLISH).parse(input);
long milliseconds = date.getTime();
long millisecondsFromNow = milliseconds - (new Date()).getTime();
Toast.makeText(this, "Milliseconds to future date="+millisecondsFromNow, Toast.LENGTH_SHORT).show();
A more difficult technique (that basically does what DateFormat does for you) involves parsing it yourself (this would not be considered best practice):
String input = "Sat Feb 17 2012";
String[] myDate = input.split("\\s+");
int year = Integer.parseInt(myDate[3]);
String monthString = myDate[1];
int mo = monthString.equals("Jan")? Calendar.JANUARY :
monthString.equals("Feb")? Calendar.FEBRUARY :
monthString.equals("Mar")? Calendar.MARCH :
monthString.equals("Apr")? Calendar.APRIL :
monthString.equals("May")? Calendar.MAY :
monthString.equals("Jun")? Calendar.JUNE :
monthString.equals("Jul")? Calendar.JULY :
monthString.equals("Aug")? Calendar.AUGUST :
monthString.equals("Sep")? Calendar.SEPTEMBER :
monthString.equals("Oct")? Calendar.OCTOBER :
monthString.equals("Nov")? Calendar.NOVEMBER :
monthString.equals("Dec")? Calendar.DECEMBER : 0;
int day = Integer.parseInt(myDate[2]);
Calendar c = Calendar.getInstance();
c.set(year, mo, day);
long then = c.getTimeInMillis();
Time current_time = new Time();
current_time.setToNow();
long now = current_time.toMillis(false);
long future = then - now;
Date d = new Date(future);
//TODO use d as you need.
Toast.makeText(this, "Milliseconds to future date="+future, Toast.LENGTH_SHORT).show();
Firts, you must parse you String to get its Date representation. Here are examples and some docs.
Then you shoud call getTime() method of your Date.
DateFormat format = new SimpleDateFormat("EEE MMM dd yyyy", Locale.US);
long futureTime = 0;
try {
Date date = format.parse("Sat Feb 17 2012");
futureTime = date.getTime();
} catch (ParseException e) {
Log.e("log", e.getMessage(), e);
}
long curTime = System.currentTimeMillis();
long diff = futureTime - curTime;
Pass year, month and day of the future date in the date of this code and variable diff will give the millisecond time till that date,
Date date = new GregorianCalendar(year, month, day).getTime();
Date today = new Date();
long diff = date.getTime() - today.getTime();
You can simply call the getTime() method of date object. please follow through the sample below
import java.util.Date;
public class Test {
#SuppressWarnings("deprecation")
public static void main(String[] args) {
System.out.println(new Date("Sat Feb 17 2012").getTime());
}
}
try { String str_date="11-June-07";
SimpleDateFormat formatter ;
Date date ;
formatter = new SimpleDateFormat("dd-MMM-yy");
date = (Date) formatter.parse(str_date);
Log.i("test",""+date);
} catch (Exception e)
{System.out.println("Exception :"+e); }
Date d = new Date();
long time = d.getTime();
long timeDiff = time - lastTime;
//timeDiff will contain your value.
//import these two,
//import java.text.SimpleDateFormat;
//import java.util.Date;

Categories

Resources