I downloaded joda library and extract joda time to calculate time difference,
Here is my class that calculate date difference: (I'm using Java 1.7)
public class TimeDiffereneceTest {
static String secondDate,firstDate, dateDifference;
public static void main(String[] args) {
firstDate = "2014/07/20";
secondDate = getTodayDate(); // Generate 2014/07/23
DateDifference(firstDate, secondDate);
}
public static String getTodayDate() {
Calendar todayDate = Calendar.getInstance();
SimpleDateFormat simpleFormat = new SimpleDateFormat("YYYY/MM/dd");
String strDate = simpleFormat.format(todayDate.getTime());
return strDate;
}
public static void DateDifference(String firstDate,String nowDate) {
Date d1=null;
Date d2=null;
SimpleDateFormat format = new SimpleDateFormat("YYYY/MM/dd");
try{
d1 = format.parse(firstDate);
d1 = format.parse(nowDate);
DateTime dt1 = new DateTime(d1);
DateTime dt2 = new DateTime(d2);
System.out.println("Day difference is: "+Days.daysBetween(dt1, dt2).getDays()); // 206!
}
catch(Exception e){
e.printStackTrace();
}
}
}
The result should be 3 because today date is 2014/07/23 and first date was "2014/07/20" , But has wrong result (206).
I see some problems with code :
1) new SimpleDateFormat should throw illegal argument becouse of "YYYY" should be"yyyy" (at least for me this works
2) In DateDifference (should be name dateDifference since its a method, not class - naming convenction)
You got
d1 = format.parse(firstDate);
d1 = format.parse(nowDate);
Instead of
d1 = simpleFormat.parse(firstDate);
d2 = simpleFormat.parse(nowDate);
Try using this code, it works for me.
public class TimeDiffereneceTest {
static String secondDate,firstDate, dateDifference;
static SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy/MM/dd");
public static void main(String[] args) {
firstDate = "2014/07/20";
secondDate = getTodayDate(); // Generate 2014/07/23
DateDifference(firstDate, secondDate);
}
public static String getTodayDate() {
Calendar todayDate = Calendar.getInstance();
String strDate = simpleFormat.format(todayDate.getTime());
return strDate;
}
public static void DateDifference(String firstDate,String nowDate) {
Date d1=null;
Date d2=null;
try{
d1 = simpleFormat.parse(firstDate);
d2 = simpleFormat.parse(nowDate);
DateTime dt1 = new DateTime(d1);
DateTime dt2 = new DateTime(d2);
System.out.println("Day difference is: "+Days.daysBetween(dt1, dt2).getDays()); // 206!
}
catch(Exception e){
e.printStackTrace();
}
}
}
Which java version are you using?
In 7, capital Y has a different meaning from y. In 6 Y is not specified so it throws the following exception:
java.lang.IllegalArgumentException: Illegal pattern character 'Y'
Your code has two issues that I can see (apart from the random unused statics).
Y is not the format code for year, y is.
d2 is null, you are parsing both strings into d1.
The following code gives me 4 when run today, '2014/07/24'.
SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
String firstDate = "2014/07/20";
String secondDate = format.format(new Date());
int days = Days.daysBetween(new DateTime(format.parse(firstDate)), new DateTime(format.parse(secondDate))).getDays();
System.out.println(days);
Related
Example, I have a monthyear on String, like this:
202108
And I want to next month by passing above month in below format:
202109
What is the best way to do this?
Java 8+ ⇒ java.time.YearMonth:
public static void main(String[] args) throws Exception {
// create a formatter for the String format you are using
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuuMM");
// use it in order to parse the String to a YearMonth
YearMonth yearMonth = YearMonth.parse("202108", dtf);
// add a month to have the next one
YearMonth nextYearMonth = yearMonth.plusMonths(1);
// and print it using the formatter
System.out.println(nextYearMonth.format(dtf));
}
Output:
202109
If you want it as a method/function, then try something like
public static String getYearMonthAfter(String month) {
// create a formatter for the String format you are using
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuuMM");
// use it in order to parse the String to a YearMonth
YearMonth yearMonth = YearMonth.parse(month, dtf);
// add a month to have the next one
YearMonth nextYearMonth = yearMonth.plusMonths(1);
// and return the resulting String by means of the formatter
return nextYearMonth.format(dtf);
}
SimpleDateFormat and Calendar can help you a lot.
public static String getNextMonth(String s) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
Calendar cal = Calendar.getInstance();
try{
cal.setTime(sdf.parse(s));
} catch (ParseException e) {
e.printStackTrace();
return "";
}
cal.add(Calendar.MONTH, 1);
return sdf.format(cal.getTime());
}
You can use add function in Calendar class to add month
public String getNextMonth(String time){
DateFormat sdf = new SimpleDateFormat("yyyyMM");
Date dt = sdf.parse(time);
Calendar c = Calendar.getInstance();
c.setTime(dt);
c.add(Calendar.MONTH, 1); //adding a month
String req_date = sdf.format(c.getTime());
return req_date;
}
This question already has answers here:
How to convert a date to milliseconds
(5 answers)
Closed 3 years ago.
How can I do that? I tried a lot but it is not working properly.
public static String getDateTime() {
String dateStr = "";
Calendar cal = Calendar.getInstance();
Date date = cal.getTime();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
dateStr = dateFormat.format(date);
return dateStr;
}
Please someone right another method which return miliseconds from above Date format. Of course! In my DB I'm storing this value: 2019-04-17 17:11:02 -> I want this value to convert in miliseconds using one method. so that I call new method and pass that variable value.
public static long milisecondsFromDate(String dateStr) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date date = formatter.parse(dateStr);
return date.getTime();
} catch (Exception e) {
Log.e("Tag", "Wrong date Format");
}
return -1;
}
I would strongly suggest to use Java8 Date/Time API for your cause, something like:
public static void main(String[] args) {
System.out.println(getDateTime());
}
public static String getDateTime() {
String dateStr = "2019-04-17 17:11:02";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
LocalDateTime localDateTime = LocalDateTime.parse(dateStr, formatter);
return String.valueOf(localDateTime.toInstant(ZoneOffset.UTC).getEpochSecond());
}
try this:-
long timeInMilliseconds = 0;
String givenDateString = "2019-04-17 17:11:02";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date mDate = sdf.parse(givenDateString);
timeInMilliseconds = mDate.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
String timeInMilliseconds = String.valueOf(timeInMilliseconds);
This question already has answers here:
Java : Cannot format given Object as a Date
(7 answers)
java.lang.IllegalArgumentException: Cannot format given Object as a Date
(4 answers)
Closed 4 years ago.
I am new to Java. I have been trying to convert a date into format dd-MMM-yy.
But i am getting exception :
Exception in thread "main" java.lang.IllegalArgumentException: Cannot format given Object as a Date
Below is my code . Please guide.
public class Test {
public static void main(String args[ ]) {
String currentDateString =new String();
DateFormat dateFormat = new SimpleDateFormat("MMM dd, yyyy");
DateFormat dateFormatpdfname = new SimpleDateFormat("dd-MMM-yy");
//Date currentDate = new Date();
String dateInString = "Sep 16, 2018";
String dateInString1 = "16-Sep-18";
String currentDateVal=dateFormatpdfname.format(dateInString1);
currentDateString = dateFormat.format(dateInString);
System.out.println(currentDateVal);
System.out.println(currentDateString);
}
}
Uncomment this
//Date currentDate = new Date();
Then,
String currentDateVal=dateFormatpdfname.format(currentDate );
currentDateString = dateFormat.format(currentDate );
Probably i was not passing it as date and that is the reason i was getting error. Below is the correct answer.
public class Test {
public static void main(String args[ ]) throws ParseException {
//Base obj1 = new Base();
// As per overriding rules this should call to class Derive's static
// overridden method. Since static method can not be overridden, it
// calls Base's display()
//Derived.display();
Date myDate = null;
String currentDateString =new String();
DateFormat dateFormat = new SimpleDateFormat("dd-MMM-yy");
// DateFormat dateFormatpdfname = new SimpleDateFormat("dd-MMM-yy");
//Date currentDate = new Date();
// String dateInString = "Sep 16, 2018";
String dateInString1 = "16-Sep-18";
myDate = dateFormat.parse(dateInString1);
//String currentDateVal=dateFormatpdfname.format(dateInString1);
currentDateString = dateFormat.format(myDate);
//String releaseDateStr = dateFormat.format(currentDateString);
// System.out.println(currentDateVal);
System.out.println(currentDateString);
}
}
I have an date object from which i need to getTime(). The issue is it always shows 00:00:00.
SimpleDateFormat localDateFormat = new SimpleDateFormat("HH:mm:ss");
long date = Utils.getDateObject(DateObject).getTime();
String time = localDateFormat.format(date);
Why is the time always '00:00:00'. Should i append Time to my Date Object
You should pass the actual Date object into format, not a long:
SimpleDateFormat localDateFormat = new SimpleDateFormat("HH:mm:ss");
String time = localDateFormat.format(Utils.getDateObject(DateObject));
Assuming that whatever Utils.getDateObject(DateObject) is actually returns a Date (which is implied by your question but not actually stated), that should work fine.
For example, this works perfectly:
import java.util.Date;
import java.text.SimpleDateFormat;
public class SDF {
public static final void main(String[] args) {
SimpleDateFormat localDateFormat = new SimpleDateFormat("HH:mm:ss");
String time = localDateFormat.format(new Date());
System.out.println(time);
}
}
Re your comment below:
Thanks TJ, but actually i am still getting 00:00:00 as time.
That means your Date object has zeroes for hours, minutes, and seconds, like so:
import java.util.Date;
import java.text.SimpleDateFormat;
public class SDF {
public static final void main(String[] args) {
SimpleDateFormat localDateFormat = new SimpleDateFormat("HH:mm:ss");
String time = localDateFormat.format(new Date(2013, 4, 17)); // <== Only changed line (and using a deprecated API)
System.out.println(time);
}
}
Apart from above solution , you can also use calendar class if you don't have specific requirement
Calendar cal1 =new GregorianCalendar() or Calendar.getInstance();
SimpleDateFormat date_format = new SimpleDateFormat("HH:mm:ss");
System.out.println(date_format.format(cal1.getTime()));
For example, you can use next code:
public static int getNotesIndexByTime(Date aDate){
int ret = 0;
SimpleDateFormat localDateFormat = new SimpleDateFormat("HH");
String sTime = localDateFormat.format(aDate);
int iTime = Integer.parseInt(sTime);
return iTime;// count of hours 0-23
}
Good Day.
I've got another problem related to Jtable.
I want to change the row color of a table if the date inside column (expiry) exceeds or is equal to the current date.
I tried this code but i get an error: java.lang.NumberFormatException: For input string: "2012-03-15"
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
String expDateString = sdf.format(cal.getTime());
System.out.println(expDateString);
Double date = Double.parseDouble(expDateString);
Double val = Double.parseDouble(tableSummary.getModel().getValueAt(row, 6).toString());
for(int i=0; i<=tableSummary.getRowCount()-1; i++){
if(val >= date){
renderer.setBackground(red);
}
}
Thanks!
here's a new code:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
String expDateString = sdf.format(cal.getTime());
Date today = new Date(expDateString);
System.out.println("ang churva is " + today);
Date given = new Date(tableSummary.getModel().getValueAt(row, 6).toString());
for(int i=0; i<=tableSummary.getRowCount()-1; i++){
if(today.compareTo(given)>=0){
renderer.setBackground(red);
}
}
but i get this exception: java.lang.IllegalArgumentException at Date today = new Date(expDateString);
Use the code
DATEDIFF('d',NOW(),exdate)
in your resultset query. It will return the difference. Alter it possibly to match your needs.
You can't cast a date string in a double
Double date = Double.parseDouble(expDateString); //does not work!
Simple example of how you can compare you dates. Note that if the objects in your JTable already are Dates, you don't need all the parsing, which would make your life easier.
The output of the code below is:
expiryDate=2012-03-15
tableDateOK=2012-03-12
tableDateExpired=2012-03-18
tableDateOK>expiryDate = false
tableDateExpired>expiryDate = true
Code:
public static void main(String args[]) throws ParseException {
String expiryDate = "2012-03-15";
String tableDateOk = "2012-03-12";
String tableDateExpired = "2012-03-18";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
System.out.println("expiryDate="+expiryDate);
System.out.println("tableDateOK="+tableDateOk);
System.out.println("tableDateExpired="+tableDateExpired);
System.out.println("tableDateOK>expiryDate = " + sdf.parse(tableDateOk).after(sdf.parse(expiryDate)));
System.out.println("tableDateExpired>expiryDate = " + sdf.parse(tableDateExpired).after(sdf.parse(expiryDate)));
}
line Double date = Double.parseDouble(expDateString);
this cannot work because string "2012-03-15" is simply not a valid double value.
I do not understand why you are trying to compare two double values:
if you have Date in table, use Date.after() and Date.before() to find out, whether your date is before or after now.
if you have String in table, use the SimpleDateFormat.parse() to get Date from it and do point 1
public String compareDate( Request request ) throws ParseException {
Date debitDate= request.getPaymentTxn().getCrValDt();
Date now = new Date();
String response="";
SimpleDateFormat sdfDate = new SimpleDateFormat("dd/MM/yyyy");
String strCurrDate = sdfDate.format(now);
String strDebitDate = sdfDate.format(debitDate);
System.out.println("Current Date: " + strCurrDate);
Date currentDate = new SimpleDateFormat("dd/MM/yyyy").parse(strCurrDate);
Date txnDate = new SimpleDateFormat("dd/MM/yyyy").parse(strDebitDate);
System.out.println("C -> "+currentDate);
System.out.println("C -> "+txnDate);
if (txnDate!=null){
if (currentDate.equals(txnDate))
{
System.out.println("Valid Txn");
response="valid";
}
if (currentDate.after(txnDate))
{
System.out.println("--> Not Valid TXN Past");
response="notValid";
}
if (currentDate.before(txnDate)){
System.out.println("Future Valid TXn");
response="future";
}
}
return response;
}
PLease Chk it out its working fine