This question already has answers here:
Adding n hours to a date in Java?
(16 answers)
Closed 7 years ago.
I have a TextView that store a getDate() value. This getDate() value is a date but the format is String
textview_device_datetime.setText(data.getDate().replace('T', ' '));
this is the result
16-08-2015 16:15:16
but i would add 2 hours to this String Date.
How can i do?
Any help is great.
Thanks
final String dateString = "16-08-2015 16:15:16";
final long millisToAdd = 7_200_000; //two hours
DateFormat format = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
Date d = format.parse(dateString);
d.setTime(d.getTime() + millisToAdd);
System.out.println("New value: " + d); //New value: Sun Aug 16 18:15:16 CEST 2015
Here I have attached the code for it with example.
import java.time.*;
import java.text.*;
import java.util.*;
public class AddTime
{
public static void main(String[] args)
{
String myTime = "16-08-2015 16:15:16";
System.out.println(addHour(myTime,2));
}
public static String addHour(String myTime,int number)
{
try
{
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
Date d = df.parse(myTime);
Calendar cal = Calendar.getInstance();
cal.setTime(d);
cal.add(Calendar.HOUR, number);
String newTime = df.format(cal.getTime());
return newTime;
}
catch(ParseException e)
{
System.out.println(" Parsing Exception");
}
return null;
}
}
Related
This question already has answers here:
How to compare dates in Java? [duplicate]
(11 answers)
Closed 5 years ago.
I'm trying to write 'isPast(String dateStr)' function, which receives date string and returns true if it's in the past and false otherwise.
private static boolean isPast(String dateStr) {
Calendar c = GregorianCalendar.getInstance();
int currentYear = c.get(Calendar.YEAR);
int currentMonth = c.get(Calendar.MONTH);
int currentDay = c.get(Calendar.DAY_OF_MONTH);
int currentHour = c.get(Calendar.HOUR_OF_DAY);
int currentMinute = c.get(Calendar.MINUTE);
c.set(currentYear, currentMonth, currentDay, currentHour, currentMinute);
Date now = c.getTime();
SimpleDateFormat sdfDates = new SimpleDateFormat("dd/m/yyyy");
Date date = null;
try {
date = sdfDates.parse(dateStr);
} catch (ParseException e) {
e.printStackTrace();
}
if (now.compareTo(date) == 1){
System.out.println(dateStr + " date given is past");
return true;
}
System.out.println(dateStr + " date given is future");
return false;
}
And i'm calling it with:
String str1 = "22/04/2018";
String str2 = "22/01/2018";
System.out.println(isPast(str1));
System.out.println(isPast(str2));
And the output is:
22/04/2018 date given is past
22/01/2018 date given is past
What is going on here? It's not true. I'm on this for too long - it should be simple, obviously i'm missing something with that Calendar object...
Use LocalDate that is available in Java 8
public static void main(String[] args) {
String str1 = "22/04/2018";
String str2 = "22/01/2018";
System.out.println(isPast(str1));
System.out.println(isPast(str2));
}
private static boolean isPast(String dateStr) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
LocalDate dates = LocalDate.parse(dateStr, formatter);
return dates.isBefore(LocalDate.now());
}
Try this:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Test {
private static final SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
public static void main(String[] args) {
String str1 = "22/04/2018";
String str2 = "22/01/2018";
String str3 = "xx/01/2018";
Date now = new Date();
testDate (str1, now);
testDate (str2, now);
testDate (str3, now);
}
private static void testDate(String str, Date now) {
try {
if (sdf.parse(str).before(now)) {
System.out.println(str + " is in the past.");
} else {
System.out.println(str + " is in the future.");
}
} catch (ParseException e) {
System.out.println("Date not in format dd/MM/yyyy : " + str);
}
}
}
Output:
22/04/2018 is in the future.
22/01/2018 is in the past.
Date not in format dd/MM/yyyy : xx/01/2018
If you have to use Calendar, try this:
private static void testDateUsingCalendar (String str, Date now) {
try {
String[] split = str.split("/");
Calendar c = GregorianCalendar.getInstance();
c.set(Integer.valueOf(split[2]), Integer.valueOf(split[1]), Integer.valueOf(split[0]));
if (c.getTime().before(now)) {
System.out.println(str + " is in the past.");
} else {
System.out.println(str + " is in the future.");
}
} catch (Exception e) {
System.out.println("Date not in format dd/MM/yyyy : " + str);
}
}
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);
I need your help in getting the list of months and the years in String between two dates. The user will enter two dates in the String format of:
String date1 ="JAN-2015";
String date2 ="APR-2015";
So the result should be:
Jan-2015
FEB-2015
MAR-2015
I tried using the following code but it gave me wrong results:
List<Date> dates = new ArrayList<Date>();
String str_date ="JAN-2015";
String end_date ="APR-2015";
DateFormat formatter ;
formatter = new SimpleDateFormat("MMM-yyyy");
Date startDate = formatter.parse(str_date);
Date endDate = formatter.parse(end_date);
long endTime =endDate.getTime() ;
long curTime = startDate.getTime();
while (curTime <= endTime) {
dates.add(new Date(curTime));
curTime ++;
}
for(int i=0;i<dates.size();i++){
Date lDate =(Date)dates.get(i);
String ds = formatter.format(lDate);
System.out.println(ds);
}
Using the less code possible and basic java libraries and getting the result you asked for. So you can modify the date1 and date2 variables.
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class Main {
public static void main(String[] args) {
String date1 = "JAN-2015";
String date2 = "APR-2015";
DateFormat formater = new SimpleDateFormat("MMM-yyyy");
Calendar beginCalendar = Calendar.getInstance();
Calendar finishCalendar = Calendar.getInstance();
try {
beginCalendar.setTime(formater.parse(date1));
finishCalendar.setTime(formater.parse(date2));
} catch (ParseException e) {
e.printStackTrace();
}
while (beginCalendar.before(finishCalendar)) {
// add one month to date per loop
String date = formater.format(beginCalendar.getTime()).toUpperCase();
System.out.println(date);
beginCalendar.add(Calendar.MONTH, 1);
}
}
}
In case your Java version is < 8 you could use Calendar as follows:
private final static DateFormat formatter = new SimpleDateFormat("MMM-yyyy", Locale.ENGLISH);
public static void main(String[] args) throws ParseException {
Calendar startDate = stringToCalendar("Jan-2015");
Calendar endDate = stringToCalendar("Apr-2015");
while (startDate.before(endDate)) {
System.out.println(formatter.format(startDate.getTime()));
startDate.add(Calendar.MONTH, 1);
}
}
private static Calendar stringToCalendar(String string) throws ParseException {
Date date = formatter.parse(string);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar;
}
If you have a luxury of Java 8 then the code becomes more simple:
public static void main(String[] args) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM-yyyy", Locale.ENGLISH);
YearMonth startDate = YearMonth.parse("Jan-2015", formatter);
YearMonth endDate = YearMonth.parse("Apr-2015", formatter);
while(startDate.isBefore(endDate)) {
System.out.println(startDate.format(formatter));
startDate = startDate.plusMonths(1);
}
}
This question already has answers here:
Convert string to Date in java
(6 answers)
Closed 8 years ago.
I have string date time "2014-10-13 18:22:54.71", I want to convert that to Date and
I'll use that algorithm
public static boolean IsthatMorethanTwo(String DateString) {
Calendar thatDay = Calendar.getInstance();
thatDay.setTime(new Date(DateString));
Calendar today = Calendar.getInstance();
long diff = today.getTimeInMillis() - thatDay.getTimeInMillis();
long days = diff / (24 * 60 * 60 * 1000);
return days >= 2;
}
How can I do this ?
You can use SimpleDateFormat class.
Like this:
String dateString = "2014-10-13 18:22:54.71";
SimpleDateFormat format =
new SimpleDateFormat("yyyy-mm-dd HH:mm:ss.S");
try {
Date parsed = format.parse(dateString);
}
catch(ParseException pe) {
System.out.println("ERROR: Cannot parse \"" + dateString + "\"");
}
This question already has answers here:
How to round time to the nearest quarter hour in java?
(17 answers)
Closed 8 years ago.
I have the following code to get datetime UTC.
public static Date GetUTCdatetimeAsDate()
{
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;
}
Now I want to use GETUTCdatetimeAsDate and if I get for example 11/22/2014 03:12 the minutes will be rounded up to the nearest 5 minutes. So in this case that will be 11/22/2014 03:15. If it is 11/22/2014 03:31 it will be 11/22/2014 03:35.
Any ideas on how to achieve this?
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 null;
}
Calendar c = Calendar.getInstance();
c.setTime(dateToReturn);
int minute = c.get(Calendar.MINUTE);
minute = minute % 5;
if (minute != 0) {
int minuteToAdd = 5 - minute;
c.add(Calendar.MINUTE, minuteToAdd);
}
return c.getTime();
}