Is there a way to add number of days to a date using java Date apis, vs hitting the database?
The date input is off format: yyyy-MM-dd, MM/dd/yyyy
Here is my current code:
public String AddToDate(String holdDate, int holdDays)
{
try
{
Database db = new Database();
String sQuery = "SELECT DATEADD(dd,?,?) AS NewDate";
Object[] param = new Object[2];
param[0] = holdDays;
param[1] = holdDate;
db.queryPS(sQuery, param);
if ( db.getRow() )
{
return db.getField("NewDate");
}
else
return "";
}
catch(Exception ex)
{
return "";
}
}
I have not tested this, but this is what I have so far:
public String AddToDate(String holdDate, int holdDays)
{
try
{
String newDate = "";
SimpleDateFormat inFormatter = new SimpleDateFormat("MM/dd/yyyy");
Date date1 = inFormatter.parse(holdDate);
Calendar cal = Calendar.getInstance();
cal.setTime(date1);
cal.add(Calendar.DATE, holdDays); // number of days to add
newDate = (inFormatter.format(cal.getTime()));
return newDate;
}
catch(Exception ex)
{
ex.printStackTrace();
return "";
}
}
Related
I have a question my date formate is d mmm,yyyy how I can sort this?
FORMAT d mmm,yyyy
I want to sort my list with a date anyone help me please in this formate how I can solve my problem?
Before you set your adapter do these changes.You can use your list model data
Recent data come into top if you want reverse change this return date2s.compareTo(date1); into return date1.compareTo(date2s); like that
Collections.sort(results, new Comparator<Result>() {
#SuppressLint("SimpleDateFormat")
#Override
public int compare(Result t1, Result t2) {
if (t1.getCreatedDate() != null) {
String sDate1 = t1.getCreatedDate();
String date2 = t2.getCreatedDate();
java.util.Date date1 = null;
Date date2s = null;
try {
date1 = new SimpleDateFormat("d mmm,yyyy").parse(sDate1);
date2s = new SimpleDateFormat("d mmm,yyyy").parse(date2);
} catch (ParseException e) {
e.printStackTrace();
}
if (date1 != null && date2s != null) {
return date2s.compareTo(date1);
}
return 0;
} else return 0;
}
});
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);
}
}
from the database postgressql i'm getting date sometime date in different different forlamts like "2015-11-26 09:30:10","2015-11-26 09:30:10.080","2015-11-26 09:30:10.000" now i want to convert all format as only this format 22/01/2018 how to do in java.
try {
Date theDate1 = new Date("JAN 13,2014 09:15");
SimpleDateFormat format1 = new SimpleDateFormat("dd/MM/yyyy");
String temp = format1.format(theDate1);
System.out.println("Hello, World! " + temp);
} catch (Exception e {
System.out.println(e.toString());
}
i got output as Hello, World !13 / 01 / 2014 but when i tried
try {
Date theDate1 = new Date("2017-11-27 00:00:00");
SimpleDateFormat format1 = new SimpleDateFormat("dd/MM/yyyy");
String temp = format1.format(theDate1);
System.out.println("Hello, World! " + temp);
} catch (Exception e) {
System.out.println(e.toString());
}
then i got java.lang.IllegalArgumentExceptionhow to solve this problem
Try this
String text = "JAN 13,2014 09:15";
String patternst = "\\d\\d\\d\\d-\\d\\d-\\d\\d*";
Pattern pattern = Pattern.compile(patternst);
Matcher matcher = pattern.matcher(text);
String data = "";
while (matcher.find()) {
data = matcher.group(0);
}
try {
int year = Integer.parseInt(data.split("-")[0]);
int month = Integer.parseInt(data.split("-")[1]);
int day = Integer.parseInt(data.split("-")[2]);
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month);
cal.set(Calendar.DAY_OF_MONTH, day);
Date theDate1 = cal.getTime();
SimpleDateFormat format1 = new SimpleDateFormat("dd/MM/yyyy");
String temp = format1.format(theDate1);
System.out.println("Hello, World! " + temp);
} catch (Exception e) {
Date theDate1 = new Date(text);
SimpleDateFormat format1 = new SimpleDateFormat("dd/MM/yyyy");
String temp = format1.format(theDate1);
System.out.println("Hello, World! " + temp);
}
Used the below code and not getting the exact output.
Desired output:
2015-09-04T11:30:06-0500 to 2015-09-04T11:30:06-05:00
Actual output:
dateValue => 2015-10-19T16:52:23-0400
a => 2015-10-20T02:22:23+0530
My code:
public class test {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String a = formattedDate("2015-10-19T16:52:23-0400");
System.out.println ("a => " + a);
}
public static String formattedDate (String dateValue) {
String expectedFormat = "";
SimpleDateFormat inputDateFormat =
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
SimpleDateFormat outputDateFormat =
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZ");
try {
System.out.println("dateValue => " + dateValue);
if (dateValue == null || dateValue.isEmpty()) {
dateValue = "";
}
inputDateFormat.setLenient(true);
Date d = inputDateFormat.parse(dateValue);
expectedFormat = outputDateFormat.format(d);
} catch (Exception e) {
// Sending back the current datetime in the desired format
Calendar cal = Calendar.getInstance();
expectedFormat = outputDateFormat.format(cal.getTime());
}
return expectedFormat;
}
}
Under Java 7 and higher, you can use XXX to output the time zone with a column:
SimpleDateFormat outputDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
When you use this to format a data, it will return for example:
2001-07-04T12:08:56-07:00
See the documentation for more examples.
Since I'm using 1.6, XXX is not supported. So used alternative way to achieve this. This is what I did for alternative way..
public static String formattedDate (String dateValue) {
StringBuilder expectedFormat;
SimpleDateFormat inputDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
try {
if (dateValue == null || dateValue.isEmpty()) {
dateValue = "";
}
inputDateFormat.setLenient(false);
Date d = inputDateFormat.parse(dateValue);
} catch (Exception e) {
System.out.println("Error in parsing : " + e.getMessage());
// Sending back the current datetime in the desired format
Calendar cal = Calendar.getInstance();
dateValue = inputDateFormat.format(cal.getTime());
} finally {
expectedFormat = new StringBuilder(dateValue).insert(dateValue.length()-2, ":");
}
return expectedFormat.toString();
}
When you need only the third last character changed and give a string as a parameter how about leaving it a String?
public static String formattedDate (String dateValue)
{
return dateValue.substring(0, dateValue.length() - 2)
+ ":"
+ dateValue.substring(dateValue.length() - 2);
}
Output:
a => 2015-10-19T16:52:23-04:00
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();
}