date comparison "after" method returns false always - android

i am trying to compare two dates using "after" method in android. here is my two dates
currentDate :Fri Sep 12 00:00:00 GMT+05:30 2014
expDate :Tue Sep 01 00:00:00 GMT+05:30 2015
my code is as follows
private boolean checkDate(String date) throws ParseException{
Calendar c = Calendar.getInstance();
String cYear = String.valueOf(c.get(Calendar.YEAR)).substring(0, 2);
String digit1 = date.substring(2,4);
String digit2 = date.substring(0, 2);
String finalDate = cYear+digit1+"-"+digit2+"-"+"01";
SimpleDateFormat curFormater = new SimpleDateFormat("yyyy-MM-dd");
Date expDate = curFormater.parse(finalDate);
String cDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
Date curentDate = curFormater.parse(cDate);
if(curentDate.after(expDate)){
return true;
}else{
return false;
}
}
but my if condition is always returns false. i don't know whats wrong with the code.
please some one help me about this..
thank you.

Related

how to convert a date in GMT format to another format?

How can i convert Fri Dec 29 05:30:00 GMT 05:30 20 into 29-12-2017 02:28:03 this format in android.i already used the below code for convert the date but i can't work.so please help me out.
String date = Fri Dec 29 05:30:00 GMT 05:30 20
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy h:mm:ss");
Date date1 = sdf.parse(date);
Below two methods to convert date as per your requirement
//method for converting TimeStamp date(long) to String... in Date
public static String makeLongTODate(long dateTime) {
Date d = new Date(dateTime);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy", Locale.ENGLISH);
String date = simpleDateFormat.format(d);
return date;
}
//method for converting TimeStamp date(long) to String... in date & Time
public static String makeLongTODateTime(long dateTime) {
Date d = new Date(dateTime);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss", Locale.ENGLISH);
String date = simpleDateFormat.format(d);
return date;
}

How to convert Java.Util.Date to System.DateTime

In Xamarin.Android, you work with both .NET and Java.
I get a return value of Java.Util.Date, I then need to input that same value as a parameter that only takes System.DateTime
This is how I currently do it
public static DateTime ConvertJavaDateToDateTime(Date date)
{
var a = date.ToGMTString();
var b = date.ToLocaleString();
var c = date.ToString();
DateTime datetime = DateTime.ParseExact(date.ToGMTString(), "dd MMM yyyy HH:mm:ss 'GMT'", CultureInfo.InvariantCulture);
return datetime;
}
However on the first 9 days of any month, I only get 1 digit for the day, and the
DateTime.ParseExact function is looking for dd (i.e. 2 digits for the day).
a is a string with value "1 Sep 2014 14:32:25 GMT"
b is a string with value "1 Sep 2014 16:32:25"
c is a string with value "Mon Sep 01 16:32:25 EET 2014"
I wish I could find a simple, quick, reliable and consistent solution for this problem :D
java.util.Date has a getTime() method, which returns the date as a millisecond value. The value is the number of milliseconds since Jan. 1, 1970, midnight GMT.
With that knowledge, you can construct a System.DateTime, that matches this value like so:
public DateTime FromUnixTime(long unixTimeMillis)
{
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
return epoch.AddMilliseconds(unixTimeMillis);
}
(method taken from this answer)
Do this:
public DateTime ConvertDateToDateTime(Date date)
{
SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd hh:mm:ss");
String dateFormated = dateFormat.format(date);
return new DateTime(dateFormated);
}
I'll update my answer, since you've changed the question.
you can use a long to hold the milliseconds and than convert the milliseconds to ticks(x10000) and create a new DateTime
Date date = new Date();
Long milliseconds = date.getTime();
Long ticks = milliseconds * 10000
DateTime datetime = DateTime(ticks);
I had this problem when authenticating with Facebook to receive the Expire time for the token. The solution was to do this:
var convertedTime = new DateTime(1970,1,1,0,0,0,DateTimeKind.Utc).AddMilliseconds(MyJavaUtil.Date.Time);
I used this:
DateTimeOffset.FromUnixTimeMilliseconds(date.Time - (date.TimezoneOffset * 60 * 1000)).DateTime;
To incorporate the timezone offset into my date.
In my case, only this code works correctly:
public static DateTime NativeDateToDateTime(Java.Util.Date date)
{
SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
string dateFormated = dateFormat.Format(date);
return DateTimeOffset.Parse(dateFormated, null, DateTimeStyles.None).DateTime;
}
It is not tested but try with Calendar methods
public static String ConvertJavaDateToDateTime(Date date)
{
Calendar c = new GregorianCalendar();
c.setTime(date);
System.out.println(c.getTime());
return c.getTime();
}
Prints:
Tue Aug 06 00:00:00 EDT 2013
You can try with this also
public DateTime dateAndTimeToDateTime(java.sql.Date date, java.sql.Time time) {
String myDate = date + " " + time;
SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy HH:mm:ss 'GMT'");
java.util.Date utilDate = new java.util.Date();
try {
utilDate = sdf.parse(myDate);
} catch (ParseException pe){
pe.printStackTrace();
}
DateTime dateTime = new DateTime(utilDate);
return dateTime;
}

How to get standard format date in android

if i try the below code for eg:
i will set the date as Fri July 25 2014 10:00 AM. which gives date in milliseconds as 1402080056000,
now if i try to read the same milliseconds to date as below
long time = 1402080056000;
Date mydate = new Date(time);
mydate variable shows date as Sat Jun 25 00:10:56 IST 2014
String DateTimeString = DateFormat.getDateTimeInstance().format(new Date(time));
with the above statement in DateTimeString i get date as Jun 25 , 2014 12:10:56 AM
How to read the datetime present in 1402080056000 to Fri July 25 2014 10:00 AM
Just need to work on the format string,
String dateTimeString=
String.valueOf(new SimpleDateFormat("dd-MM-yyyy hh:mm").format(new Date(time)));
Explicitly set time zone:
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm");
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
String result = String.valueOf(dateFormat.format(millis));
Also, this would be useful Regarding Timezones and Java
try below code:
private String convertMilliToDate(long timestamp) {
DateFormat formatter = new SimpleDateFormat("YOUR DATE FORMAT");
// Create a calendar object that will convert the date and time value in
// milliseconds to date.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(time);
return formatter.format(calendar.getTime());
}
Try this:
String date= DateFormat.format("dd/MM/yyyy hh:mm:ss", new Date(date_in_milis)).toString();
Date-time work is easier using the Joda-Time library, which works on Android.
long millis = 1402080056000L;
DateTimeZone timeZoneIndia = DateTimeZone.forID( "Asia/Kolkata" );
DateTime dateTimeIndia = new DateTime( millis, timeZoneIndia );
DateTime dateTimeFrance = dateTimeIndia.withZone( DateTimeZone.forID( "Europe/Paris" ) );
DateTime dateTimeUtc = dateTimeIndia.withZone( DateTimeZone.UTC );
To parse a string as a date-time, search StackOverflow for "Joda parse" to find many examples.

To get Date and time from Timestamp Android

I want to get time and date separately from timestamp.Please help me in these. My example of timestamp is 1378798459.
Thanks
//Try the following
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String dateString = formatter.format(new Date(Long.parseLong(YOUR TIMESTAMP VALUE)));
txtDate.setText(dateString);
//You can put your needed format here:
SimpleDateFormat formatter = new SimpleDateFormat("YOUR REQUIRED FORMAT");
Try this is working with me
public String getDateCurrentTimeZone(long timestamp) {
try{
Calendar calendar = Calendar.getInstance();
TimeZone tz = TimeZone.getDefault();
calendar.setTimeInMillis(timestamp * 1000);
calendar.add(Calendar.MILLISECOND, tz.getOffset(calendar.getTimeInMillis()));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date currenTimeZone = (Date) calendar.getTime();
return sdf.format(currenTimeZone);
}catch (Exception e) {
}
return "";
}
Improving upon the answer given by Pratik Dasa
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Here you can get various formats using the following syntax. You can play around with it by deleting or adding terms given below in the syntax.
Date and Time Pattern Result
----------------------------- ---------------------------------
"yyyy.MM.dd G 'at' HH:mm:ss z" 2001.07.04 AD at 12:08:56 PDT
"EEE, MMM d, ''yy" Wed, Jul 4, '01
"h:mm a" 12:08 PM
"hh 'o''clock' a, zzzz" 12 o'clock PM, Pacific Daylight Time
"K:mm a, z" 0:08 PM, PDT
"yyyyy.MMMMM.dd GGG hh:mm aaa" 02001.July.04 AD 12:08 PM
"EEE, d MMM yyyy HH:mm:ss Z" Wed, 4 Jul 2001 12:08:56 -0700
"yyMMddHHmmssZ" 010704120856-0700
"yyyy-MM-dd'T'HH:mm:ss.SSSZ" 2001-07-04T12:08:56.235-0700
"yyyy-MM-dd'T'HH:mm:ss.SSSXXX" 2001-07-04T12:08:56.235-07:00
"YYYY-'W'ww-u" 2001-W27-3
String time = DateUtils.formatDateTime(this, 1378798459, DateUtils.FORMAT_SHOW_TIME);
String date = DateUtils.formatDateTime(this, 1378798459, DateUtils.FORMAT_SHOW_DATE);
Try this,
final Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(System.currentTimeMillis());
Date date = cal.getTime();
mHour = date.getHours();
mMinute = date.getMinutes();
Only that:
long timestampString = Long.parseLong("yourString");
String value = new java.text.SimpleDateFormat("dd/MM/yyyy HH:mm:ss").
format(new java.util.Date(timestampString * 1000));
long dv = Long.valueOf(timestamp_in_string)*1000;// its need to be in milisecond
Date df = new java.util.Date(dv);
String vv = new SimpleDateFormat("MM dd, yyyy hh:mma").format(df);
From here.
you can use this
Long tsLong = System.currentTimeMillis();
String ts = tsLong.toString();
long millisecond = Long.parseLong(ts);
datetimeString = DateFormat.format("MM-dd-yyyy hh:mm:ss a", new Date(millisecond)).toString();
timeString = datetimeString.substring(11);
dateString = datetimeString.substring(0,10);
String t2 = datetimeString.substring(20,21);
The datetimeString contains the Date Time AM/PM data
timeString will give you the substring which contains the time only and the dateString is substring for date
The String t2 will give you whether it is AM or PM in the clock
int day, month, year;
int second, minute, hour;
GregorianCalendar date = new GregorianCalendar();
day = date.get(Calendar.DAY_OF_MONTH);
month = date.get(Calendar.MONTH);
year = date.get(Calendar.YEAR);
second = date.get(Calendar.SECOND);
minute = date.get(Calendar.MINUTE);
hour = date.get(Calendar.HOUR);
String data =(hour+ ':'+ ""+minute+ ':'+"" +second+"" +""+"" +day+"" +"/" +(month+1)+"" +"/"+ +year);
Toast.makeText(getActivity(), "Time stamp:"+data,Toast.LENGTH_LONG).show();
DateFormat dateFormat = DateFormat.getDateTimeInstance();
when.setText(dateFormat.format(new Date(timestamp * 1000)));
The timestamp is multiplied by 1000 for converting the seconds into milliseconds.
All the answers are great and they mainly focus on converting the unix timestamp to milliseconds first, which is correct.
I struggled to apply that because I must use 1000L in the conversion (instead of 1000 only). Here's my working code with time zone conversion
// Set TimeZone
SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd-yy h:mm a", Locale.US);
dateFormat.setTimeZone(getDeviceTimeZone());
// Set time
Date date = new Date(timestamp * 1000L);
return dateFormat.format(date);
For Android API 26 and above, you can just do
return Instant.ofEpochSecond( timestamp )
.atZone(ZoneId.of( timezone ))
.toLocalDateTime()
.toString();
The very best way to get day and date from the timestamp is that:
java.util.Date dayAndDate = new java.util.Date( (long) yourTimeStamp * 1000);
// object coming as like: Tue Feb 09
String day = dayAndDate.toString().split(" ")[0];
String month = dayAndDate.toString().split(" ")[1];
String date = dayAndDate.toString().split(" ")[2];
I hope you will like my approach, if you have liked it, don't forget to give it an upvote, so that others will consider it.
If you want to use time like in a WhatsApp message, You can use this method,
public static String millisToDateChat(long time) {
long currentTime = System.currentTimeMillis();
long defe = currentTime - time;
long time_in;
if(time!=0){
time_in = time;
}else{
time_in = currentTime;
defe = 0;
}
int s = (int)defe/1000;
int m = (int)defe/(1000*60);
int h = (int)defe/(1000*60*60);
int d = (int)defe/(1000*60*60*24);
int w = (int)defe/(1000*60*60*24*7);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(time_in);
Date date = calendar.getTime();
#SuppressLint("SimpleDateFormat") String formattedDate=(new SimpleDateFormat("HH:mm")).format(date);
#SuppressLint("SimpleDateFormat") String formattedYear=(new SimpleDateFormat("MMM d, ''yy")).format(date);
#SuppressLint("SimpleDateFormat") String formattedm=(new SimpleDateFormat("MMM d")).format(date);
if(d>365) {
return formattedYear;
}else if(s>172000){
return formattedm;
}else if(s>86400) {
return "Yest.";
}else{
return formattedDate;
}
}

Android Date Time Format getting wrong time to display 12 hours and 24 hours

Here I found some problem to maintain one simple date response to get 12 hours and 24 hours. Both time are different in one date format.
Code which I have used currently:
My Date String Response = "2011-12-12T19:41:15.17Z"
Code
private static final SimpleDateFormat dateFormatToolTipResponse = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
private SimpleDateFormat cunsultationPostTimezone12 = new SimpleDateFormat("MM/dd/yy hh:mm a z");
private SimpleDateFormat cunsultationPostTimezone24 = new SimpleDateFormat("MM/dd/yy HH:MM z");
public String formateDateTimeConsultation(String dateTime)
{
StringBuffer strResult = new StringBuffer();
strResult.append(getPostTimecunsultation(parseDate(dateTime)));
return strResult.toString();
}
private static Date parseDate(String date)
{
try {
return dateFormatToolTipResponse.parse(date);
} catch ( Exception e ){
return null;
}
}
private String getPostTimecunsultation(Date date)
{
if(date != null){
if(ConstantCodes.is24Hours)
{
return cunsultationPostTimezone24.format(date);
}
else
{
return cunsultationPostTimezone12.format(date);
}
}
return "";
}
========================================
Here is my output
24 hours = 12/12/11 11:12 PST
12 hours = 12/12/11 11:42 AM PST
I couldn't find what's wrong in this.
Please can you suggest some ideas?
you set the MM in the time in 24 format
private SimpleDateFormat cunsultationPostTimezone24 = new SimpleDateFormat("MM/dd/yy HH:MM z");
so you always getting Month value Caps M will give you the Month value while small m for minute change with this below line and then try
private SimpleDateFormat cunsultationPostTimezone24 = new SimpleDateFormat("MM/dd/yy HH:mm z");

Categories

Resources