setting particular date to Date object - android

I've been trying this from a long time.
I'm having today's date and I want to compare it with specific date.
But when I set particular date like this, it gives me wrong output:
Calendar cal;
SimpleDateFormat dateformatter;
String currentdate;
cal = Calendar.getInstance();
dateformatter = new SimpleDateFormat("yyyy-MM-dd");
//Getting today's date
currentdate = dateformatter.format(cal.getTime());
Log.i(Class_Tag, "current = " + currentdate);
//Setting specific date
Date start = cal.getTime();
cal.set(2012, 06, 20);
Date end = cal.getTime();
Log.i(Class_Tag, "end = " + dateformatter.format(end));
long diff = end.getDate() - start.getDate();
Log.i(Class_Tag, "diff : " + diff);
long diff1 = end.getMonth() - start.getMonth();
Log.i(Class_Tag, "diff mnth : " + diff1);
long diff2 = end.getYear() - start.getYear();
Log.i(Class_Tag, "diff yr : " + diff2);
if (start.compareTo(end) == 0) {
Log.i(Class_Tag, "EQUAL");
} else if (start.compareTo(end) < 0) {
Log.i(Class_Tag, "end b4 start, delete");
} else {
Log.i(Class_Tag, "start b4 end, do nothing");
OUTPUT:
current = 2012-06-20
end = 2012-07-20 ////WHY it is showing month as '7' when I've set it to '6'?
diff : 0
diff mnth : 1 //Because of the wrong month in end date, this comes 1 instead of 0
diff yr : 0
end b4 start, delete //this also is not correct
I've tried several solutions, but no gains.
My only objective is to get whether that particular date has passed today's date or not.
Any help appreciated.
Edit
in the following code snippet,
//Setting specific date
Date start = cal.getTime();
cal.set(2012, 06, 20);
Date end = cal.getTime();
If I set cal.set(2012, 06, 20); to cal.set(2012, 05, 20);, the month diff. comes out to 0.
This implies that month in particular date is getting incremented by '1', but WHY?

Try this;
Calendar cal = Calendar.getInstance();
long dateNowMillis = cal.getTimeInMillis();
cal.set(2013, 1, 23);
long specDate = cal.getTimeInMillis();
if(dateNowMillis > specDate)
{
System.out.println("Passed");
}
else if(dateNowMillis == specDate)
{
System.out.println("Now");
}
else
{
System.out.println("Not passed");
}

FYI,
A month is represented by an integer from 0 to 11; 0 is January, 1 is February, and so forth; thus 11 is December.
You can check read more about Date here and more about SimpleDateFormat.
Update:
One more thing about getMonth() => Its deprecated, instead Calendar.get(Calendar.MONTH), check here.

Related

How to set alarm manager using date and time from Textview

I am converting a timestamp into date and time and setting the result on a textview.
For example 1443884578 is Sat 3 October 2015 18:02
I would like to set the above date and time into an alarm manager.After research i found a code that uses a date time picker.
public void onDateSelectedButtonClick(View v) {
// Get the date from our datepicker
int day = picker.getDayOfMonth();
int month = picker.getMonth();
int year = picker.getYear();
// Create a new calendar set to the date chosen
// we set the time to midnight (i.e. the first minute of that day)
Calendar c = Calendar.getInstance();
c.set(year, month, day);
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
// Ask our service to set an alarm for that date, this activity talks to the client that talks to the service
scheduleClient.setAlarmForNotification(c);
// Notify the user what they just did
Toast.makeText(this, "Notification set for: " + day + "/" + (month + 1) + "/" + year, Toast.LENGTH_SHORT).show();
}
However its getting only the date and fires the alarm the minute the date occurs.
PROBLEM: I would like to get the date and time from my textview and skip this date time picker in the format i have. Is this possible?
String input = "Sat October 3 2015 18:02"; // Instead of String input = "Mon Feb 06 2015";
Calendar cal = Calendar.getInstance();
Date date = new Date();
// Changed the format to represent time of day
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss", Locale.ENGLISH);
try {
date = sdf.parse(input);
} catch (ParseException e) {
e.printStackTrace();
}
cal.setTime(date);
//We haven't parsed the seconds from the original date so this will result
//in 18:02:00 - 10seconds.
//For a correct calculation, you could parse the seconds as well
//See SimpleDateFormat above, but you would have to provide the original date
//with seconds as well
cal.add(Calendar.SECOND, -10);
scheduleClient.setAlarmForNotification(cal);

Android how to customize date in listview

I want to show the date from current date on words in list view .How to customize that date.Could please any one tell me.For example when u booking ticket in railways it's showing the current date on-wards.Like that i want to implement.
![enter image description here][1]
[1]: http://i.stack.imgur.com/3NPXA.png
use the SimpleDateFormat for example
Date d = new Date();
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("c - LLLL");
String formattedDate = simpleDateFormat.format(d);//Mon - June for that format
Check the formats (yyyy,dd ...) in SimpleDateFormat
Hope this will help.
Code for checking date after or before today.
Calendar c = Calendar.getInstance();
// set the calendar to start of today
c.set(Calendar.HOUR, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
// and get that as a Date
Date today = c.getTime();
// or as a timestamp in milliseconds
long todayInMillis = c.getTimeInMillis();
// user-specified date which you are testing
// let's say the components come from a form or something
int year = 2011;
int month = 5;
int dayOfMonth = 20;
// reuse the calendar to set user specified date
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
c.set(Calendar.DAY_OF_MONTH, dayOfMonth);
// and get that as a Date
Date dateSpecified = c.getTime();
// test your condition
if (dateSpecified.before(today)) {
System.err.println("Date specified [" + dateSpecified + "] is before today [" + today + "]");
} else {
System.err.println("Date specified [" + dateSpecified + "] is NOT before today [" + today + "]");
}
Done

Calculating date certain period from now

I have a start date (day, month, year) and need the date say 4 weeks from that date. How can I calculate that? I know how to find the difference between two dates using Calendar so I assume I'm not too far from the answer... Thank you!!!
edit:
This is the final code I wound up using. It returns a String whose value is a date span formatted "MM/dd/YYYY - MM/dd/YYYY"
#SuppressLint("SimpleDateFormat")
private String getSessionDate(int position) {
MySession ms = mSessionList.get(position);
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
Calendar calendar = Calendar.getInstance();
calendar.set(ms.getStartYear(), ms.getStartMonth(), ms.getStartDay());
Date startDate = calendar.getTime();
String durationString = ms.getDurationString(); // Format is "## weeks"
int i = 0;
while (Character.isDigit(durationString.charAt(i))) {
i++;
}
int weeks = Integer.parseInt(durationString.substring(0, i));
calendar.add(Calendar.WEEK_OF_YEAR, weeks);
return (format.format(startDate) + " - " + format.format(calendar.getTime()));
}
You can use Calender instance for that.
Calendar calendar = Calendar.getInstance();
calendar.setTime(currentdate);
calendar.add(Calendar.DAY_OF_YEAR, no_of_days)
Date newDate = calendar.getTime();
You can calculate the date by adding or subtracting the no of days
Example :
Get date after 1 week
calendar.add(Calendar.DAY_OF_YEAR, 7);
Get date before 1 week
calendar.add(Calendar.DAY_OF_YEAR, -7);
Date date=null;
SimpleDateFormat originalFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
date = originalFormat.parse(strDate); // strDate is your date from which you want to get date after 4 weeks
} catch (Exception e) {
e.printStackTrace();
}
long timeFor4week=4*7*24 * 60 * 60 * 1000; /// here 24*60*60*1000 =24 hours i.e 1 day
long timeAfter4week=date.getTime()+timeFor4week;
String finalDateString=originalFormat.format(new Date(timeAfter4week));
So you can get day after 4 weeks.

Convert Date to Year and Month

I am writing an application in which I have to display a date . Now I want to convert that date into Year and Month from the Current Date.
My Date is Like - 29/03/2017.
I want to convert this date into Year and Months.
Sorry I think you are not able to understand my question. I want the Difference of current date and above date in year and months.
Sorry for my explanation.
You can use Joda Time and compute a Period between two LocalDate values (which is what you've got here) using months and years as the units.
example
LocalDate dob = new LocalDate(1992, 12, 30);
LocalDate date = new LocalDate(2010, 12, 29);
Period period = new Period(dob, date, PeriodType.yearMonthDay());
System.out.println(period.getYears() + " years and " +
period.getMonths() + " months");
I found my answer using Calender class .
First i find the difference between two days and using that days i found the years and months.
Here i post my code, which i think help to others.
int days = Integer.parseInt(Utility.getDateDiffString("29/03/2017"));
int years = days/365;
int remainingDays = days - (365*years);
int months = remainingDays/30;
getDateDiffString() Method. In this method we need to pass end date
public static String getDateDiffString(String endDate)
{
try
{
Calendar cal = Calendar.getInstance();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date dateTwo = dateFormat.parse(endDate);
long timeOne = cal.getTimeInMillis();
long timeTwo = dateTwo.getTime();
long oneDay = 1000 * 60 * 60 * 24;
long delta = (timeTwo - timeOne) / oneDay;
if (delta > 0) {
return "" + delta + "";
}
else {
delta *= -1;
return "" + delta + "";
}
}
catch (Exception e)
{
e.printStackTrace();
}
return "";
}
if your date's format is fixed, you can do it like this :
String myDate = "29/03/2017";
String newDate = myDate.subString(6, 10) + "-" + myDate.subString(3, 5)
this method to convert the normal string to date format
String currentDateString = "02/27/2012 17:00:00";
SimpleDateFormat sd = new SimpleDateFormat("mm/dd/yyyy HH:mm:ss");
Date currentDate = sd.parse(currentDateString);
after that you get the formal method
You Should use SimpleDateFormate !
For Example:--- You can get time & Date as you want:-
Date email_date = m.getSentDate();// this is date which you are getting
DateFormat date = new SimpleDateFormat("EEE MMM yyyy");
DateFormat time = new SimpleDateFormat("hh:mm aa");
String date_str=date.format(email_date);
String time_str=time.format(email_date);
Use Java Calendar class to get year from date
Calendar c=Calendar.getInstance();
SimpleDateFormat simpleDateformat=new SimpleDateFormat("yyyy MMM");
System.out.println(simpleDateformat.format(c.getTime()));
To get difference between two date
int diffInDays = (int)( (newerDate.getTime() - olderDate.getTime())
/ (1000 * 60 * 60 * 24) )
long timeDiff = (d1.getTime() - d2.getTime());
String diff=String.format("%d year(s) %d day(s) %d hour(s) %d min(s) %d sec(s)",(TimeUnit.MILLISECONDS.toDays(timeDiff)/365),TimeUnit.MILLISECONDS.toDays(timeDiff)%365,
TimeUnit.MILLISECONDS.toHours(timeDiff)
- TimeUnit.DAYS.toHours(TimeUnit.MILLISECONDS
.toDays(timeDiff)),
TimeUnit.MILLISECONDS.toMinutes(timeDiff)
- TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS
.toHours(timeDiff)),
TimeUnit.MILLISECONDS.toSeconds(timeDiff)
- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS
.toMinutes(timeDiff)));
System.out.println(diff);
Specify correct date here in d1 & d2.Then you will get right answer of difference
First put your Date into a String variable as:
String dateToConvert = "29/03/2017";
Instantiate Calendar as:
Calendar convertedDate = Calendar.getInstance();
Set that date to calendar
convertedDate.set(dateToConvert);<br/>
Then use this line:
String datePicked = DateFormat.getDateInstance().format(convertedDate.getTime());
Output: Mar 29, 2017

Get Date of past 7days from current in android

I am trying to fetch the date 7days prior to today's date.
I am using SimpleDateFormat to fetch today's date.
SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy");
Please guide me through this
Updated answer which I found most useful
SimpleDateFormat sdf=new SimpleDateFormat("dd/MM/yyyy");
String currentDateandTime = sdf.format(new Date());
Date cdate=sdf.parse(currentDateandTime);
Calendar now2= Calendar.getInstance();
now2.add(Calendar.DATE, -7);
String beforedate=now2.get(Calendar.DATE)+"/"+(now2.get(Calendar.MONTH) + 1)+"/"+now2.get(Calendar.YEAR);
Date BeforeDate1=sdf.parse(beforedate);
cdate.compareTo(BeforeDate1);
Thank you for you reply
Use java.util.Calendar, set it to today's date and then subtract 7 days.
Calendar cal = GregorianCalendar.getInstance();
cal.setTime(new Date());
cal.add(Calendar.DAY_OF_YEAR, -7);
Date 7daysBeforeDate = cal.getTime();
Edit: In Java 8 it can be done much easier by using classes from java.time package:
final LocalDate date = LocalDate.now();
final LocalDate dateMinus7Days = date.minusDays(7);
//Format and display date
final String formattedDate = dateMinus7Days.format(DateTimeFormatter.ISO_LOCAL_DATE);
System.out.println(formattedDate);
You can try out this,
import java.util.Calendar;
public class AddDaysToCurrentDate {
public static void main(String[] args) {
//create Calendar instance
Calendar now = Calendar.getInstance();
System.out.println("Current date : " + (now.get(Calendar.MONTH) + 1)
+ "-"
+ now.get(Calendar.DATE)
+ "-"
+ now.get(Calendar.YEAR));
//add days to current date using Calendar.add method
now.add(Calendar.DATE,1);
System.out.println("date after one day : " + (now.get(Calendar.MONTH) + 1)
+ "-"
+ now.get(Calendar.DATE)
+ "-"
+ now.get(Calendar.YEAR));
//substract days from current date using Calendar.add method
now = Calendar.getInstance();
now.add(Calendar.DATE, -10);
System.out.println("date before 10 days : " + (now.get(Calendar.MONTH) + 1)
+ "-"
+ now.get(Calendar.DATE)
+ "-"
+ now.get(Calendar.YEAR));
}
}
/*
Typical output would be
Current date : 12-25-2007
date after one day : 12-26-2007
date before 10 days : 12-15-2007
*/
Android get date before 7 days (one week)
Date myDate = dateFormat.parse(dateString);
And then either figure out how many milliseconds you need to subtract:
Date newDate = new Date(myDate.getTime() - 604800000L); // 7 * 24 * 60 * 60 * 1000
Or use the API provided by the java.util.Calendar class:
Calendar calendar = Calendar.getInstance();
calendar.setTime(myDate);
calendar.add(Calendar.DAY_OF_YEAR, -7);
Date newDate = calendar.getTime();
Then, if you need to, convert it back to a String:
and finally
String date = dateFormat.format(newDate);
you can use this kotlin function to get any date before the current date.
/**
* get specific date before current date
* [day] number of day
* [month] number of month
* [year] number of year
* [count] number of day, month, year
*
* return date
*/
fun getBeforeDate(day: Boolean = false, month: Boolean = false, year: Boolean = false, count: Int = 0): String{
val currentCalendar = Calendar.getInstance()
val myFormat = "dd/MM/yyyy" // you can use your own date format
val sdf = SimpleDateFormat(myFormat, Locale.getDefault())
if (day){
currentCalendar.add(Calendar.DAY_OF_YEAR, -count)
}else if(month){
currentCalendar.add(Calendar.MONTH, -count)
}else if(year){
currentCalendar.add(Calendar.YEAR, -count)
}else{
// if user not provide any value then give current date
currentCalendar.add(Calendar.DAY_OF_YEAR, 0)
// or you can throw Exception
//throw Exception("Please provide at least one value")
}
return sdf.format(currentCalendar.time)
}
fun getBeforeDate(day: Boolean = false, month: Boolean = false, year: Boolean = false, count: Int = 0): String{
val currentCalendar = Calendar.getInstance()
val myFormat = "dd/MM/yyyy" // you can use your own date format
val sdf = SimpleDateFormat(myFormat, Locale.getDefault())
if (day){
currentCalendar.add(Calendar.DAY_OF_YEAR, -count)
}else if(month){
currentCalendar.add(Calendar.MONTH, -count)
}else if(year){
currentCalendar.add(Calendar.YEAR, -count)
}else{
// if user not provide any value then give current date
currentCalendar.add(Calendar.DAY_OF_YEAR, 0)
// or you can throw Exception
//throw Exception("Please provide at least one value")
}
return sdf.format(currentCalendar.time)
}

Categories

Resources