This question already has answers here:
How can I increment a date by one day in Java?
(32 answers)
Closed 6 years ago.
I'm working on an android application and new to it.
I have to get date from user and then add 28 days and store it in database.
This is what I have done so far
private void saveDate() throws ParseException {
DatabaseHelper db = new DatabaseHelper(ActivityPeriodToday.this.getActivity());
String pDate = periodDate.getText().toString().trim();
String pTime = periodTime.getText().toString().trim();
String next_expected = getNextExpected(pDate);
boolean isInserted = db.insertPeriodTodayIntoPeriods(pDate, pTime, early_late, pDifference, pType, next_expected);
if (isInserted == true) {
Toast.makeText(ActivityPeriodToday.this.getActivity(), "Saved", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(ActivityPeriodToday.this.getActivity(), "Could not be saved", Toast.LENGTH_SHORT).show();
}
}
private String getNextExpected(String pDate) {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Calendar c = Calendar.getInstance();
try {
c.setTime(sdf.parse(pDate));
} catch (ParseException e) {
e.printStackTrace();
}
c.add(Calendar.DAY_OF_MONTH, 28);
return sdf.format(c.getTime());
}
But is code is not incrementing month.
Ex. If user selects 01/11/2016, then date is incremented and is saved
29/11/2016. But if user selects 16/11/2016 then saves date is
28/11/2016 but this should be 14/12/2016
Step 1
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
c.setTime(sdf.parse(dateInString));
Step-2 use add() to add number of days to calendar
c.add(Calendar.DATE, 40);
Try using this:
calendar.add(Calendar.DAY_OF_YEAR, 28);
Its Working for me.
Calendar c = Calendar.getInstance();
int Year = c.get(Calendar.YEAR);
int Month = c.get(Calendar.MONTH);
int Day = c.get(Calendar.DAY_OF_MONTH);
// current date
String CurrentDate = Year + "/" + Month + "/" + Day;
String dateInString = CurrentDate; // Start date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
c = Calendar.getInstance();
try {
c.setTime(sdf.parse(dateInString));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
c.add(Calendar.DATE, 28);//insert the number of days that you want
sdf = new SimpleDateFormat("dd/MM/yyyy");
Date resultdate = new Date(c.getTimeInMillis());
dateInString = sdf.format(resultdate);
Toast.makeText(MainActivity.this, ""+dateInString, Toast.LENGTH_SHORT).show();
Your question may already have an answer here: How can I increment a date by one day in Java?
Or you can simply use
c.add(Calendar.DATE, 28);
instead of
c.add(Calendar.DAY_OF_MONTH, 28);
Related
I getting two date from calendars.It writing into a string builder.I want to getting difference between two date also I want to keep the number of days remaining between times,except weekends.
private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
// when dialog box is closed, below method will be called.
public void onDateSet(DatePicker view, int selectedYear, int selectedMonth, int selectedDay) {
year = selectedYear;
month = selectedMonth;
day = selectedDay;
if (cur == DATE_DIALOG_ID) {
// set selected date into textview
permitDate = new StringBuilder().append(day).append(".").append(month + 1).append(".").append(year).append(" ").toString();
tvDisplayDate.setText("Date : " + permitDate);
} else {
startDate = new StringBuilder().append(day).append(".").append(month + 1) .append(".").append(year).append(" ").toString();
tvDisplayDate2.setText("Date : " + startDate);
}
}
};
Calendar thatDay = Calendar.getInstance();
thatDay.set(Calendar.DAY_OF_MONTH,25);
thatDay.set(Calendar.MONTH,7); // 0-11 so 1 less
thatDay.set(Calendar.YEAR, 1985);
Calendar today = Calendar.getInstance();
long diff = today.getTimeInMillis() - thatDay.getTimeInMillis(); //result in millis
long days = diff / (24 * 60 * 60 * 1000);
To Parse the date from a string, you could use
String strThatDay = "1985/08/25";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
Date d = null;
try {
d = formatter.parse(strThatDay);//catch exception
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Calendar thatDay = Calendar.getInstance();
thatDay.setTime(d); //rest is the same....
Use JodaTime library to find the difference between dates.
For more information follow the instructions Use Joda Time.
Is there any other easy way to convert "Aug/2016" to "08/2016" in java?
My Logic is working fine, but seems too vague.
String myDate = "Aug/2016";
String str = myDate.split("/")[0];
Date date;
try {
date = new SimpleDateFormat("MMMM").parse(str);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
System.out.println("##### ----- month in number : " +cal.get(Calendar.MONTH+1));
int year = Calendar.getInstance().get(Calendar.YEAR);
int mnth = cal.get(Calendar.MONTH) + 1;
str = String.valueOf(mnth+"/"+year);
System.out.println("##### ----- new selected date : " +str);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
suggestions please!...
Simply use SimpleDateFormat:
String myDate = "Aug/2016";
SimpleDateFormat parser = new SimpleDateFormat("MMM/yyyy");
SimpleDateFormat formatter = new SimpleDateFormat("MM/yyyy");
System.out.println(formatter.format(parser.parse(myDate)));
I have a timestamp and I want to check whether the time is before or after a certain time (9:00 AM). To be more specific, I want to know whether a person is late or not and the cut-off time is 9 AM. How do I code this?
2015-09-22 08:59:59 //Print on time
2015-09-22 09:00:00 //Print on time
2015-09-22 09:00:01 //Print you are late
I think you can do like:
public static final String TIME_STAMP_FORMAT = "yyyy-MM-dd HH:mm:ss";
public static void main(String[] args) {
Date standard = getStandardDate();
SimpleDateFormat format = new SimpleDateFormat(TIME_STAMP_FORMAT);
List<String> data = new ArrayList<String>();
data.add("2015-09-22 08:59:59");
data.add("2015-09-22 09:00:00");
data.add("2015-09-22 09:00:01");
for (String date : data) {
if(isLate(date, format)) {
System.out.println(date + " is Late");
} else {
System.out.println(date + " is On Time");
}
}
}
/**
* check is Late or not
* */
public static boolean isLate(String date, SimpleDateFormat format) {
Date standard = getStandardDate();
Date inputDate = null;
boolean result = false;
try {
inputDate = format.parse(date);
if(inputDate.after(standard)) {
result = true;
}
} catch (ParseException e) {
e.printStackTrace();
}
return result;
}
/**
* get standard date
* */
public static Date getStandardDate() {
Date dateNow = new Date ();
Calendar cal = Calendar.getInstance();
cal.setTime(dateNow);
cal.set(Calendar.DAY_OF_MONTH, 22);
cal.set(Calendar.HOUR_OF_DAY, 9);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
return cal.getTime();
}
Hope this help!
You can have code similar to following
// Get the provided date and time
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar providedDate = Calendar.getInstance();
providedDate.setTime(df.parse(stringInstanceRepresentingDate));
// Get the current date and time
Calendar cal = Calendar.getInstance();
// Set time of calendar to 09:00
cal.set(Calendar.HOUR_OF_DAY, 9);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
// Check if current time is after 09:00 today
boolean afterNine = providedDate.after(cal);
if (afterNine ) {
System.out.println("You are late");
}
else {
System.out.println("You are not late");
}
Assuming the input is a String, you can do the following
String input = ...;
String time = input.split(" ")[1],
hour = time.split(":")[0],
minute = time.split(":")[1],
seconds = time.split(":")[2];
if(Integer.parseInt(hour) > 9 && Integer.parseInt(minute) > 0) {
// Not on time
}
This is assuming the input is always perfect though, you should use try-catch blocks or check the input beforehand as this could throw exceptions.
LocalDateTime time = LocalDateTime.of(2015, 9, 22, 9, 0, 0);
LocalDateTime now = LocalDateTime.now();
if (now.compareTo(time) > 0)
System.out.println("You are late");
else System.out.println("You are in time");
If you are working with strings you have to split them first, as mentioned by #Deximus
I want interval date. Whatever user enter date from date picker and from this date I want to get after one month date Suppose 1 Aug 2014 -> Output will be 1 September 2014.Can someone help me .Thanks to appreciate.
Hare is my Activity code
{
// Get current date by calender
final Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
// Month is 0 based, just add 1
etReplacementDate.setText(new StringBuilder()
.append(month + 1).append("-").append(day).append("-")
.append(year).append(" "));
etReplacementDate.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
showDialog(DATE_OF_REPLACEMENT);
}
});
String fixedDate = etReplacementDate.getText().toString().trim();
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss aa");
Date convertedDate = new Date();
try
{
convertedDate = dateFormat.parse(fixedDate);
}
catch (ParseException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Date Consersion = " + convertedDate);
/****************ReplaceMent Date***************************************************/
cal2.add(Calendar.getInstance(convertedDate), 30);
Date date_30dayslater = cal2.getTime();
System.out.println("date_30dayslater : " + date_30dayslater);
/****************Interval Date***************************************************/
String _30daysLater_String = new SimpleDateFormat("yyyy-MM-dd").format(date_30dayslater);
etNextReplanishmentDate.setText(_30daysLater_String);
System.out.println("30 days later: " + _30daysLater_String);
System.out.println("______________________________________");
/****************Before Date***************************************************/
cal2.add(Calendar.DATE, -1);
Date beforDate = cal2.getTime();
String beforDate_String = new SimpleDateFormat("yyyy-MM-dd").format(beforDate);
System.out.println("beforDate_String: " + beforDate_String);
}
#Override
protected Dialog onCreateDialog(int id)
{
switch (id)
{
case DATE_OF_REPLACEMENT:return new DatePickerDialog(this, pickerListenerReplacement, year, month, day);
}
return null;
}
private DatePickerDialog.OnDateSetListener pickerListenerReplacement = new DatePickerDialog.OnDateSetListener() {
// when dialog box is closed, below method will be called.
#Override
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
year = selectedYear;
month = selectedMonth;
day = selectedDay;
// Show selected date
etReplacementDate.setText(new StringBuilder().append(month + 1)
.append("-").append(day).append("-").append(year)
.append(" "));
}
};
}
What you want to do is add() one Calendar.MONTH to a date that you've gotten and parsed, etc. so I won't go into that. I'll assume you are handling everything correctly up to the point where you'd like to get the same day, if possible, of the next month.
Part of your problem, as your comment suggests, is Calendar.getInstance() does not have an implementation that takes a Date. But more importantly you don't need it. You have a Date and a Calendar instance and it seems like you're changing c2 anyway so why not use Calendar's setTime() method like this?
// setting c2 with the convertedDate then adding a month
c2.setTime(convertedDate);
c2.add(Calendar.MONTH, 1);
// Simple example
public static void main(String...args) {
Date d = new Date();
Calendar c = Calendar.getInstance();
c.setTime(d);
System.out.println(c.getTime());
c.add(Calendar.MONTH, 1);
System.out.println(c.getTime());
}
try to use this.
Calendar c = Calendar.getInstance();
int month = c.get((Calendar.MONTH));
c.set(Calendar.MONTH, month + 1);
long time = c.getTimeInMillis();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String result = sdf.format(new Date(time1));
I have a date format like "SA25MAY"; I need to convert it into date time variable and then I want to add one day in that. And then I need to return the answer in same format. Please do some needful
try {
String str_date = "SA25MAY";
DateFormat formatter;
Date date;
formatter = new SimpleDateFormat("ddd-dd-MMM");
date = (Date) formatter.parse(str_date);
System.out.println("Today is " + date);
} catch (Exception e) {
e.printStackTrace();
}
ERROR:
java.text.ParseException: Unparseable date: "SA25MAY"
at java.text.DateFormat.parse(DateFormat.java:337)
at javadatatable.JavaDataTable.main(JavaDataTable.java:29)
Here I don't know how to resolve this problem.
ddd can not match SUN. Use EEE instead if you want to match the day name in the week.
You can only add one day if you know the year because of leap years (29th of February).
In case the year is the current year, the following solution should do the the job:
For "SA25MAY":
try {
String str_date = "SA25MAY";
// remove SA
str_date = str_date.replaceFirst("..", "");
// add current year
Calendar c = Calendar.getInstance();
str_date = c.get(Calendar.YEAR) + str_date;
// parse date
Date date;
SimpleDateFormat formatter = new SimpleDateFormat("yyyyddMMM");
date = formatter.parse(str_date);
System.out.println("Today is " + date);
// add day
c.setTime(date);
c.add(Calendar.DATE, 1);
// rebuild the old pattern with the new date
SimpleDateFormat formatter2 = new SimpleDateFormat("EEEddMMM");
String tomorrow = formatter2.format(c.getTime());
tomorrow = tomorrow.toUpperCase();
tomorrow = tomorrow.substring(0, 2) + tomorrow.substring(3);
System.out.println("Tomorrow is " + tomorrow);
} catch (Exception e) {
e.printStackTrace();
}
Or for "SA-25-MAY":
try {
String str_date = "SA-25-MAY";
// remove SA
str_date = str_date.replaceFirst("..-", "");
// add current year
Calendar c = Calendar.getInstance();
str_date = c.get(Calendar.YEAR) + "-" + str_date;
// parse date
Date date;
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-dd-MMM");
date = formatter.parse(str_date);
System.out.println("Today is " + date);
// add day
c.setTime(date);
c.add(Calendar.DATE, 1);
// rebuild the old pattern with the new date
SimpleDateFormat formatter2 = new SimpleDateFormat("EEE-dd-MMM");
String tomorrow = formatter2.format(c.getTime());
tomorrow = tomorrow.toUpperCase();
tomorrow = tomorrow.substring(0, 2) + tomorrow.substring(3);
System.out.println("Tomorrow is " + tomorrow);
} catch (Exception e) {
e.printStackTrace();
}