I am using two functions to compare date values where I will be checking to see if start date is greater than/comes after the end date.
The 1st function is used to take in string value and use that string value to initialize the Calendar:
private int getFromCalendar(String strDate,int field)
{
int result = -1;
try
{
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");// this is your date format "12/24/2013" = "MM/dd/yyy"
java.util.Date date = formatter.parse(strDate);//convert to date
Calendar cal = Calendar.getInstance();// get calendar instance
cal.setTime(date);//set the calendar date to your date
result = cal.get(field); // get the required field
return result;//return the result.
}
catch (ParseException e)
{
e.printStackTrace();
}
return result;
}
The 2nd function is used to compare the startDate and endDate (they are both buttons):
public void compareDates(String startDate, String endDate){
Calendar startCheckDate = Calendar.getInstance();
int startmm = getFromCalendar(monitoringDate.getText().toString(), Calendar.MONTH);
int startyy = getFromCalendar(monitoringDate.getText().toString(), Calendar.YEAR);
int startdd = getFromCalendar(monitoringDate.getText().toString(), Calendar.DAY_OF_MONTH);
startCheckDate.set(startyy, startmm, startdd);
Calendar endCheckDate = Calendar.getInstance();
int endmm = getFromCalendar(monitoringEndDate.getText().toString(), Calendar.MONTH);
int endyy = getFromCalendar(monitoringEndDate.getText().toString(), Calendar.YEAR);
int enddd = getFromCalendar(monitoringEndDate.getText().toString(), Calendar.DAY_OF_MONTH);
endCheckDate.set(endyy, endmm, enddd);
if(endCheckDate.after(startCheckDate)){
Toast.makeText(getSherlockActivity(), "End date cannot be smaller than start date", Toast.LENGTH_SHORT).show();
}
}
For some reason the compareDates function does not work at all. Help please
You can easily compare date by changing it to milliseconds since 1900
Date date = new Date();
long dateLong = date.getTime();
Now its easy to compare with any other date
So for your case after doing this get back in date DataType
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");// this is your date format "12/24/2013" = "MM/dd/yyy"
java.util.Date date = formatter.parse(strDate);
do something like
long date1long = date1.getTime();
long date2long = date2.getTime();
if(date2long > date1long)
{
// Do whatever you want
}
This is the easiest way to compare two dates
You are way to verbose. Since you only wanted to know if a given date is after another, or not. Here you go:
public class DateTest {
private static SimpleDateFormat formatter = new SimpleDateFormat(
"MM/dd/yyyy");
public static void main(String[] args) throws ParseException {
Calendar start = createFromString("01/30/2013");
Calendar end = createFromString("06/30/2013");
System.out.println("START: " + start.getTime());
System.out.println("END : " + end.getTime());
System.out.println("IS B4: " + isBefore(start, end));
}
public static Calendar createFromString(String date) throws ParseException {
Calendar c = Calendar.getInstance();
c.setTime(formatter.parse(date));
return c;
}
public static boolean isBefore(Calendar start, Calendar end) {
return start.before(end);
}
}
OUTPUT
START: Wed Jan 30 00:00:00 CET 2013
END : Sun Jun 30 00:00:00 CEST 2013
IS B4 : true
I usesd getTime() in the println() method since, the toString() method (that gets implicitly called) on java.util.Date is more human readable than the one in Calendar.
There is also an after() in Calendar and a compareTo().
in the compareDates() use
if(endCheckDate.compareTo(startCheckDate)<0)
instead of
if(endCheckDate.after(startCheckDate))
for more reference go here
Related
I have a date like this Tue Jun 21 14:47:37 GMT+05:30 2016 , which I create myself. I create it using calendar. Where user selects a date and I save it as milliseconds from calendar.
When I send it , send it, I again create a calendar instance put the saved milliseconds into it and get the date like this :
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getDefault());
calendar.setTimeInMillis(SSPreferences.getDate());
Now while getting date from calendar i do this :
calendar.getTime()//This is what I send to server.
I send it to server, but when server sends me the date, it is always 5.5 hours before my time.
I know my time is GMT+5:50. So what server is doing on its side ?
How do I send the date , such that I get back the same date which I sent to the server.
Any help is appreciated.
Thanks
check this
static final String DATEFORMAT = "yyyy-MM-dd HH:mm:ss"
public static Date GetUTCdatetimeAsDate()
{
//note: doesn't check for null
return StringDateToDate(GetUTCdatetimeAsString());
}
public static String GetUTCdatetimeAsString()
{
final SimpleDateFormat sdf = new SimpleDateFormat(DATEFORMAT);
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(DATEFORMAT);
try
{
dateToReturn = (Date)dateFormat.parse(StrDate);
}
catch (ParseException e)
{
e.printStackTrace();
}
return dateToReturn;
}
Finally I solved the issue by adding/subtracting the rawOffSet from the local time zone.
TimeZone timeZone = TimeZone.getDefault();
int offset = timeZone.getOffset(SSPreferences.getDate());
WriteLog.Print("offset is "+offset);
long newtime = SSPreferences.getDate() + offset;
calendar.setTimeInMillis(newtime);
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;
I need to compare two dates.
which I read one of them from my database that its type is String. so first i convert String to Date in the specific format that i need, then I get the second Date from system again in the format that I want.
my problem is even when they are same i get unexpected result.
my code is:
public class SaharDateComparerActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sahar_date_comparer);
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
String dateString ="18/02/2015";
Date datee = convertStringToDate(dateString);
Log.i("SAHAR","date 1: "+ dateFormat.format(datee).toString());
Date myDate = new Date();
Log.i("SAHAR", "date 2: "+dateFormat.format(myDate).toString());
int testttt= datee.compareTo(myDate);
boolean a = datee.toString().equals(myDate.toString());
Log.i("SAHAR", "date compared: "+String.valueOf(testttt));
Log.i("SAHAR", "date equal: "+String.valueOf(a));
}
public Date convertStringToDate(String strDate) {
// String startDateString = "06/27/2007";
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Date date = null;
try {
date = df.parse(strDate);
String newDateString = df.format(date);
System.out.println(newDateString);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
}
as you can see my two dates are same but i get -1 when i use compareTo() and false when i use equals() method!!!
You should compare your Date objects after clearing the time units missing in the date coming from the database i.e. without hours, minutes, seconds etc. This is what is affecting your results.
String dateString ="18/02/2015";
Date datee = convertStringToDate(dateString);
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
Log.i("SAHAR", "Comparison result: " + datee.equals(c.getTime()));
It's because the two dates have differnt hour,minutes,seconds,... (you don't see when you just do the toString() output)
You can remove them: Compare two dates in Java
Or you make your own Comperator where you just check the day/month/year.
public static final String inputFormat = "HH:mm";
private Date date;
private Date dateCompareOne;
private Date dateCompareTwo;
LINE 5:
private String compareStringOne = String.valueOf(SetTimeActivity.intFromTimeH)+ ":"+ String.valueOf(SetTimeActivity.intFromTimeM) ;
LINE 6:
private String compareStringTwo = String.valueOf(SetTimeActivity.intToTimeH) + ":"+ String.valueOf(SetTimeActivity.intToTimeM);
SimpleDateFormat inputParser = new SimpleDateFormat(inputFormat, Locale.US);
private void compareDates()
{
Calendar now = Calendar.getInstance();
int hour = now.get(Calendar.HOUR_OF_DAY);
int minute = now.get(Calendar.MINUTE);
date = parseDate(hour + ":" + minute);
dateCompareOne = parseDate(compareStringOne);
dateCompareTwo = parseDate(compareStringTwo);
if (!(dateCompareOne.before( date ) && dateCompareTwo.after(date))) {
....
I am trying to check if current time falls between the specified time. For that I am converting the specified time into strings first (in Line5 & Line6). Even though I get the integer values correct, the string formed always shows "0:0".
Also, the year is shown as 1970 (The date & the day shown are wrong as well).
I need to get the current time. What am I doing wrong?
private Date parseDate(String date) {
try {
return inputParser.parse(date);
} catch (java.text.ParseException e) {
return new Date(0);
}
}
The parseDate() function returns the time elapsed since the 1st of January 1970. This is known as the Unix Epoch, and it's how all time is represented in Unix computers. By running the parseDate function on a string containing just hours and minutes, you're creating a Date object which represents a time HH:mm past the first of January 1970.
Your code is using a really odd way of getting the current time. Converting a Calendar to two ints, then to a string and finally parsing back to a Date is going to be inefficient and open you up to all sorts of needless errors.
When you initialise a new Date object it is automatically assigned the time of initialisation. Therefore:
Date d = new Date();
would result in d being the moment of initialisation (that is, this year, month, day, hour, minute, second and microsecond). Then you can just use Date.after() and Date.before().
If you still want to do it via the Calendar method, then you'd be better served by:
cal = Calendar.getInstance();
Date d = cal.getTime();
It may be that you've got other issues, but it's worth doing it properly first. When you pass data by writing it as a string (especially when it's time related, with all sorts of ambiguities about what "12" actually represents) you lose all the advantages that language typing gives you.
this code help you
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE); if (c.get(Calendar.AM_PM) == Calendar.AM)
am_pm = "AM";
else if (c.get(Calendar.AM_PM) == Calendar.PM)
am_pm = "PM";
// Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss a");
String formattedDate = df.format(c.getTime());
Toast.makeText(this, formattedDate, Toast.LENGTH_SHORT).show();
If you already work with Date objects why not using the Date.after(...) and Date.before(...) methods.
I store current time in database each time application starts by user.
Calendar c = Calendar.getInstance();
String str = c.getTime().toString();
Log.i("Current time", str);
In database side, I store current time as string (as you see in above code). Therefore, when I load it from database, I need to cast it to Date object. I saw some samples that all of them had used "DateFormat". But my format is exactly as same as Date format. So, I think there is no need to use "DateFormat". Am I right?
Is there anyway to directly cast this String to Date object? I want to compare this stored time with current time.
update
Thanks all. I used following code:
private boolean isPackageExpired(String date){
boolean isExpired=false;
Date expiredDate = stringToDate(date, "EEE MMM d HH:mm:ss zz yyyy");
if (new Date().after(expiredDate)) isExpired=true;
return isExpired;
}
private Date stringToDate(String aDate,String aFormat) {
if(aDate==null) return null;
ParsePosition pos = new ParsePosition(0);
SimpleDateFormat simpledateformat = new SimpleDateFormat(aFormat);
Date stringDate = simpledateformat.parse(aDate, pos);
return stringDate;
}
From String to Date
String dtStart = "2010-10-15T09:27:37Z";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
try {
Date date = format.parse(dtStart);
System.out.println(date);
} catch (ParseException e) {
e.printStackTrace();
}
From Date to String
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
try {
Date date = new Date();
String dateTime = dateFormat.format(date);
System.out.println("Current Date Time : " + dateTime);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
Date d = dateFormat.parse(datestring)
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MyClass
{
public static void main(String args[])
{
SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy");
String dateInString = "Wed Mar 14 15:30:00 EET 2018";
SimpleDateFormat formatterOut = new SimpleDateFormat("dd MMM yyyy");
try {
Date date = formatter.parse(dateInString);
System.out.println(date);
System.out.println(formatterOut.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
}
}
here is your Date object date
and the output is :
Wed Mar 14 13:30:00 UTC 2018
14 Mar 2018
using SimpleDateFormat or DateFormat class through
for e.g.
try{
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); // here set the pattern as you date in string was containing like date/month/year
Date d = sdf.parse("20/12/2011");
}catch(ParseException ex){
// handle parsing exception if date string was different from the pattern applying into the SimpleDateFormat contructor
}
You can use java.time in Android now, either by using Android API Desugaring or importing the ThreeTenAbp.
With java.time enabled, you can do the same operations with less code and less errors.
Let's assume you are passing a String containing a datetime formatted in ISO standard, just as the currently accepted answer does.
Then the following methods and their usage in a main may show you how to convert from and to String:
public static void main(String[] args) {
String dtStart = "2010-10-15T09:27:37Z";
ZonedDateTime odt = convert(dtStart);
System.out.println(odt);
}
and
public static void main(String[] args) {
String dtStart = "2010-10-15T09:27:37Z";
OffsetDateTime odt = convert(dtStart);
System.out.println(odt);
}
will print the line
2010-10-15T09:27:37Z
when there are the corresponding methods
public static OffsetDateTime convert(String datetime) {
return OffsetDateTime.parse(datetime);
}
or
public static ZonedDateTime convert(String datetime) {
return ZonedDateTime.parse(datetime);
}
but of course not in the same class, that would not compile...
There's a LocalDateTime, too, but that would not be able to parse a zone or offset.
If you want to use custom formats for parsing or formatting output, you can utilize a DateTimeFormatter, maybe like this:
public static void main(String[] args) {
String dtStart = "2010-10-15T09:27:37Z";
String converted = ZonedDateTime.parse(dtStart)
.format(DateTimeFormatter.ofPattern(
"EEE MMM d HH:mm:ss zz uuuu",
Locale.ENGLISH
)
);
System.out.println(converted);
}
which will output
Fri Oct 15 09:27:37 Z 2010
For an OffsetDateTime, you would need to adjust the pattern a little:
public static void main(String[] args) {
String dtStart = "2010-10-15T09:27:37Z";
String converted = OffsetDateTime.parse(dtStart)
.format(DateTimeFormatter.ofPattern(
"EEE MMM d HH:mm:ss xxx uuuu",
Locale.ENGLISH
)
);
System.out.println(converted);
}
This will produce a (slightly) different output:
Fri Oct 15 09:27:37 +00:00 2010
That's because a ZonedDateTime considers named time zones with changing offsets (due to daylight saving times or anything similar) while an OffsetDateTime just knows an offset from UTC.
It could be a good idea to be careful with the Locale upon which c.getTime().toString(); depends.
One idea is to store the time in seconds (e.g. UNIX time). As an int you can easily compare it, and then you just convert it to string when displaying it to the user.
String source = "24/10/17";
String[] sourceSplit= source.split("/");
int anno= Integer.parseInt(sourceSplit[2]);
int mese= Integer.parseInt(sourceSplit[1]);
int giorno= Integer.parseInt(sourceSplit[0]);
GregorianCalendar calendar = new GregorianCalendar();
calendar.set(anno,mese-1,giorno);
Date data1= calendar.getTime();
SimpleDateFormat myFormat = new SimpleDateFormat("20yy-MM-dd");
String dayFormatted= myFormat.format(data1);
System.out.println("data formattata,-->"+dayFormatted);