I have a String expired date. But I need to perform some SQL statement the day before expired date falls. I get my expired date and by:
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
String expiredDate = null;
String currentDate = dateFormat.format(new Date());
Calendar cal = Calendar.getInstance();
try {
cal.setTime(dateFormat.parse(loanDate));
cal.add(Calendar.WEEK_OF_YEAR, 2);
expiredDate = dateFormat.format(cal.getTimeInMillis());
cal.add(Calendar.WEEK_OF_YEAR, -2);
} catch (ParseException e) {
e.printStackTrace();
}
Then, I got an if statement to perform SQL statement:
if(expiredDate.equals(currentDate)){
promptExtensionDialog();
}
What I am trying to achieve is for the if statement, instead of the expiredDate itself, I need to get one day before the expired date and compare with the current date. I wonder how to achieve this?
Thanks in advance.
EDIT
try {
cal.setTime(dateFormat.parse(expiredDate));
cal.add(Calendar.DATE, -1);
expiredDate = dateFormat.format(cal.getTimeInMillis());
} catch (ParseException e) {
e.printStackTrace();
}
Toast.makeText(LoanBook.this,
expiredDate, Toast.LENGTH_LONG)
.show();
This returns me the next date instead of previous date. Do you have any ideas?
Using Java's (pre-8) built-in Date and Time API will eat you alive. Use JodaTime for complex DateTime manipulations.
Getting the previous day is as simple as this.
DateTime dateTime = new DateTime();
System.out.println(dateTime);
System.out.println(dateTime.minusDays(1));
If you don't want any external libraries:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String strDate = "2014-10-28";
Date date = sdf.parse(strDate);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DATE, -1);
Date yesterday = calendar.getTime();
System.out.println(yesterday);
System.out.println(date);
Have you tried JodaTime? It is a fantastic library to do date manipulation easily. In fact, a lot of Java 8 date handling are derived from JodaTime.
For your needs, you could do something like:
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy");
DateTime dt = formatter.parseDateTime(expiredDate);
DateTime dayBefore = dt.minusDays(1);
The other two answers are basically correct. But they omit the crucial issue of time zones and start of day. If you want all of yesterday, do something like the following.
DateTimeZone zone = DateTimeZone.forID( "America/Montreal" );
DateTime now = DateTime.now( zone );
DateTime yesterdayStart = now.minusDays( 1 ).withTimeAtStartOfDay();
Convert to a java.sql.Timestamp.
java.sql.Timestamp ts = new java.sql.Timestamp( yesterdayStart.getMillis() );
Related
I have the following code:
// OLD DATE
String date = "Mon, 06/07";
DateFormat df = new SimpleDateFormat("MM/dd");
String strDate = date.substring(date.length() - 5);
Date dateOld;
try {
dateOld = df.parse(strDate);
} catch (Exception e) {
e.printStackTrace();
}
String dateStr = df.format(dateOld);
MonthDay monthDay = MonthDay.parse(dateStr, DateTimeFormatter.ofPattern("MM/dd"));
ZonedDateTime dateNew = ZonedDateTime.now().with(monthDay);
// NEW DATE
System.out.println(dateNew.format(DateTimeFormatter.ofPattern("uuuu-MM-dd'T00:00:00Z'")));
Basically what I am trying to do is change Mon, 06/07 format to this format 2021-06-07T00:00:00Z.
What I have works, but it is really terrible. What would be a better way of doing it?
This is a little tricky as you need to make some assumptions
The year, as it's not specified in the original format
TimeZone, as it's not specified at all (the final output seems to point to UTC)
The first thing your need to do, is parse the String input into a LocalDate (you could just go straight to ZonedDate, but this is where I started)
String date = "Mon, 06/07";
DateTimeFormatter parseFormatter = new DateTimeFormatterBuilder()
.appendPattern("E, M/d")
.parseDefaulting(ChronoField.YEAR, 2021)
.toFormatter(Locale.US);
LocalDate ld = LocalDate.parse(date, parseFormatter);
Then you need to convert that to LocalDateTime
LocalDateTime ldt = ld.atStartOfDay();
And then, to a ZonedDateTime. Here' I've assumed UTC
//ZoneId zoneId = ZoneId.systemDefault();
//ZonedDateTime zdt = ldt.atZone(zoneId);
OffsetDateTime zdt = ldt.atOffset(ZoneOffset.UTC);
And finally, format the result to your desired format
String formatted = zdt.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
System.out.println(formatted);
Which, for me, prints...
2021-06-07T00:00:00Z
A lot of time and effort has gone into the new Date/Time APIs and you should make the time to try and learn them as best you can (I'm pretty rusty, but with a little tinkering, got to a result)
Maybe start with Date/Time trails
A solution use Calendar, Date and SimpleDateFormat
SimpleDateFormat sdf = new SimpleDateFormat("EEE, MM/dd", Locale.getDefault());
try {
Date oldDate = sdf.parse("Mon, 06/07");
Calendar calendar = Calendar.getInstance();
int savedYear = calendar.get(Calendar.YEAR);
if (oldDate != null) {
calendar.setTime(oldDate);
calendar.set(Calendar.YEAR, savedYear);
sdf.applyPattern("yyyy-MM-dd'T00:00:00Z'");
System.out.println(sdf.format(calendar.getTime()));
}
} catch (ParseException e) {
e.printStackTrace();
}
I am using the following date code to format the date from dd-mm-yyyy to yyyy-mm-dd hh:mm:ss. But for some days I mistakenly used the following code in production:
try {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
java.util.Date utilDate = format.parse("22-10-2016 00:00:00");
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
System.err.println(sqlDate);
} catch (Exception e) {
}
which gives date as 0028-04-07.
So now in my case I have around 300 entries which are malformed due to it, is there any way get the correct date back?
I have seen the pattern followed by dates:
23-10-2016 --> 0029-04-07
24-10-2016 --> 0030-04-08
25-10-2016 --> 0031-04-08
26-10-2016 --> 0032-04-07
So working on it till someone helps.
I am optimistic about what the solution provides.
It may not be clear to you, but by putting 2016 in the days, Java automatically rolled it forward. So where your year would have been 23, it's been pushed forward nearly 6 years.
I think this sample code, will get you quite a ways. I'm banking on the idea that, since this is a support issue and not going unnoticed for very long, it only affects 2016.
public static void main(String[] args) throws IOException
{
try
{
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date utilDate = format.parse("0030-04-07");
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
Calendar cal = Calendar.getInstance();
cal.setTime(utilDate);
cal.add(Calendar.DAY_OF_MONTH, -(2016-1));
System.out.println(cal.get(Calendar.YEAR));
System.out.println(cal.get(Calendar.MONTH));
System.out.println(cal.get(Calendar.DAY_OF_MONTH));
System.out.println(cal.get(Calendar.HOUR));
System.out.println(cal.get(Calendar.MINUTE));
System.out.println(cal.get(Calendar.SECOND));
Date time = cal.getTime();
System.err.println(time);
cal.set(Calendar.DAY_OF_MONTH, cal.get(Calendar.YEAR));
cal.set(Calendar.YEAR, 2016);
time = cal.getTime();
System.err.println(sqlDate);
System.out.println(time);
}
catch (Exception e)
{
e.printStackTrace();
}
}
I have a lot of Strings in the format shown my example that I have to parse. I'm trying to determine which of the Strings are today.
My problem is, that the time is almost there and I just need to compare that date.
Next I want to check if time is between two timestamps "HH:mm:ss" with .after and .before, but there is the problem, that the date is almost there.
How do I split that parsed format in date and time to handle each in its own way?
I'm working in Android Studio, if that's relevant.
String dtStart = "2016-05-23 07:24:59";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
if (new Date().equals(format.parse(dtStart)) ) System.out.println("true");
else System.out.println("false");
list.add(new LatLng(lat, lng));
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
java.time
Use the java.time classes built into Java 8 and later.
Much of the functionality has been back-ported to Java 6 & 7 in ThreeTen-Backport, and further adapted to Android in ThreeTen-ABP.
String dateToParse = "2016-05-23 07:24:59";
LocalDateTime dateTime = LocalDateTime.parse(dateToParse, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
LocalDate localDate = dateTime.toLocalDate();
LocalTime localTime = dateTime.toLocalTime();
// Compare here to your date & time
You can easily achieve it by using the SimpleDateFormat like that:
//Houres - seconds
SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
//Years - days
Date hoursAndMinutes = timeFormat.parse(dtStart);
Date yearsMonthsDays = dateFormat.parse(dtStart);
That way, you only get the hours, minutes and seconds of your date.
Then, you can do the same for just the year and month and compare it afterwards.
And just to be complete, here's how you'd do it using the Joda date time library and the toLocalDate() and toLocalTime() method.
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
DateTime today = new DateTime();
DateTime start = formatter.parseDateTime(dtStart);
if (today.toLocalDate().compareTo(start.toLocalDate()) != 0) {
System.out.println("true");
} else {
System.out.println("false");
}
if (today.toLocalTime().compareTo(start.toLocalTime()) > 0) {
...
}
thx for help and sry i forgot to say i'm on android studio..
i found my solution here: https://docs.oracle.com/javase/7/docs/api/java/text/DateFormat.html
String dtStart = "2016/05/23 07:24:59";
SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
try {
Date dtStartOK = format.parse(dtStart);
String stringDate = DateFormat.getDateTimeInstance().format(dtStartOK);
System.out.println(stringDate);
System.out.println(DateFormat.getDateInstance().format(dtStartOK));
System.out.println(DateFormat.getTimeInstance().format(dtStartOK));
} catch (ParseException e) {
//Handle exception here, most of the time you will just log it.
e.printStackTrace();
}
gives me:
23.05.2016 07:24:59
23.05.2016
07:24:59
My code:
Calendar calendar = DateProvider.getCalendarInstance(TimeZone.getTimeZone("GMT"));
calendar.setTime(date);
calendar.set(Calendar.YEAR, 1970);
calendar.set(Calendar.MONTH, Calendar.JANUARY);
calendar.set(Calendar.DATE, 1);
date = calendar.getTime();
Timestamp epochTimeStamp = new Timestamp(date.getTime());
I want to eliminate the use of time stamp in this situation, how can achieve the same thing here with epochTimeStamp without using java.sql.Timestamp? I need the format to be same as if I was using Timestamp.
Since you need a String representation of your Date, then use SimpleDateFormat to convert the Date object into a String:
Calendar calendar = ...
//...
date = calendar.getTime();
Timestamp epochTimeStamp = new Timestamp(date.getTime());
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
try {
System.out.println(sdf.format(date));
System.out.println(sdf.format(epochTimeStamp));
} catch (Exception e) {
//handle it!
}
From your example, prints
01/01/1970 09:21:18
01/01/1970 09:21:18
This gives you the epoch time in the same format as TimeStamp:
public class FormatDate {
public static void main(String[] args) {
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd kk:mm:ss:SSS");
LocalDateTime datetime = LocalDateTime.of(1970, 1, 1, 0, 0);
System.out.println(datetime.format(format));
}
}
Another way to represent date time objects in Java is to use the Joda Time libraries.
import org.joda.time.LocalDate;
...
LocalDate startDate= new LocalDate();//"2014-05-06T10:59:45.618-06:00");
//or DateTime startDate = new DateTime ();// creates instance of current time
String formatted =
startDate.toDateTimeAtCurrentTime().toString("MM/dd/yyy HH:mm:ss");
There are several ways to do formatting, setting and getting Time using these libraries that has been more reliable than using the JDK Date and Calendar libraries. These will persist in hibernate/JPA as well. If nothing else, this hopefully gives you options.
How to convert calendar date to yyyy-MM-dd format.
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
Date date = cal.getTime();
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
String date1 = format1.format(date);
Date inActiveDate = null;
try {
inActiveDate = format1.parse(date1);
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
This will produce inActiveDate = Wed Sep 26 00:00:00 IST 2012. But what I need is 2012-09-26. My purpose is to compare this date with another date in my database using Hibernate criteria. So I need the date object in yyyy-MM-dd format.
A Java Date is a container for the number of milliseconds since January 1, 1970, 00:00:00 GMT.
When you use something like System.out.println(date), Java uses Date.toString() to print the contents.
The only way to change it is to override Date and provide your own implementation of Date.toString(). Now before you fire up your IDE and try this, I wouldn't; it will only complicate matters. You are better off formatting the date to the format you want to use (or display).
Java 8+
LocalDateTime ldt = LocalDateTime.now().plusDays(1);
DateTimeFormatter formmat1 = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH);
System.out.println(ldt);
// Output "2018-05-12T17:21:53.658"
String formatter = formmat1.format(ldt);
System.out.println(formatter);
// 2018-05-12
Prior to Java 8
You should be making use of the ThreeTen Backport
The following is maintained for historical purposes (as the original answer)
What you can do, is format the date.
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(cal.getTime());
// Output "Wed Sep 26 14:23:28 EST 2012"
String formatted = format1.format(cal.getTime());
System.out.println(formatted);
// Output "2012-09-26"
System.out.println(format1.parse(formatted));
// Output "Wed Sep 26 00:00:00 EST 2012"
These are actually the same date, represented differently.
Your code is wrong. No point of parsing date and keep that as Date object.
You can format the calender date object when you want to display and keep that as a string.
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
Date date = cal.getTime();
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
String inActiveDate = null;
try {
inActiveDate = format1.format(date);
System.out.println(inActiveDate );
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
java.time
The answer by MadProgrammer is correct, especially the tip about Joda-Time. The successor to Joda-Time is now built into Java 8 as the new java.time package. Here's example code in Java 8.
When working with date-time (as opposed to local date), the time zone in critical. The day-of-month depends on the time zone. For example, the India time zone is +05:30 (five and a half hours ahead of UTC), while France is only one hour ahead. So a moment in a new day in India has one date while the same moment in France has “yesterday’s” date. Creating string output lacking any time zone or offset information is creating ambiguity. You asked for YYYY-MM-DD output so I provided, but I don't recommend it. Instead of ISO_LOCAL_DATE I would have used ISO_DATE to get this output: 2014-02-25+05:30
ZoneId zoneId = ZoneId.of( "Asia/Kolkata" );
ZonedDateTime zonedDateTime = ZonedDateTime.now( zoneId );
DateTimeFormatter formatterOutput = DateTimeFormatter.ISO_LOCAL_DATE; // Caution: The "LOCAL" part means we are losing time zone information, creating ambiguity.
String output = formatterOutput.format( zonedDateTime );
Dump to console…
System.out.println( "zonedDateTime: " + zonedDateTime );
System.out.println( "output: " + output );
When run…
zonedDateTime: 2014-02-25T14:22:20.919+05:30[Asia/Kolkata]
output: 2014-02-25
Joda-Time
Similar code using the Joda-Time library, the precursor to java.time.
DateTimeZone zone = new DateTimeZone( "Asia/Kolkata" );
DateTime dateTime = DateTime.now( zone );
DateTimeFormatter formatter = ISODateTimeFormat.date();
String output = formatter.print( dateTime );
ISO 8601
By the way, that format of your input string is a standard format, one of several handy date-time string formats defined by ISO 8601.
Both Joda-Time and java.time use ISO 8601 formats by default when parsing and generating string representations of various date-time values.
java.util.Date object can't represent date in custom format instead you've to use SimpleDateFormat.format method that returns string.
String myString=format1.format(date);
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
cal.set(year, month, date);
SimpleDateFormat format1 = new SimpleDateFormat("yyyy MM dd");
String formatted = format1.format(cal.getTime());
System.out.println(formatted);
}
In order to parse a java.util.Date object you have to convert it to String first using your own format.
inActiveDate = format1.parse( format1.format(date) );
But I believe you are being redundant here.
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 7);
Date date = c.getTime();
SimpleDateFormat ft = new SimpleDateFormat("MM-dd-YYYY");
JOptionPane.showMessageDialog(null, ft.format(date));
This will display your date + 7 days in month, day and year format in a JOption window pane.
public static String ThisWeekStartDate(WebDriver driver) {
Calendar c = Calendar.getInstance();
//ensure the method works within current month
c.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
System.out.println("Before Start Date " + c.getTime());
Date date = c.getTime();
SimpleDateFormat dfDate = new SimpleDateFormat("dd MMM yyyy hh.mm a");
String CurrentDate = dfDate.format(date);
System.out.println("Start Date " + CurrentDate);
return CurrentDate;
}
public static String ThisWeekEndDate(WebDriver driver) {
Calendar c = Calendar.getInstance();
//ensure the method works within current month
c.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
System.out.println("Before End Date " + c.getTime());
Date date = c.getTime();
SimpleDateFormat dfDate = new SimpleDateFormat("dd MMM yyyy hh.mm a");
String CurrentDate = dfDate.format(date);
System.out.println("End Date " + CurrentDate);
return CurrentDate;
}
I found this code where date is compared in a format to compare with date field in database...may be this might be helpful to you...
When you convert the string to date using simpledateformat, it is hard to compare with the Date field in mysql databases.
So convert the java string date in the format using select STR_to_DATE('yourdate','%m/%d/%Y') --> in this format, then you will get the exact date format of mysql date field.
http://javainfinite.com/java/java-convert-string-to-date-and-compare/
My answer is for kotlin language.
You can use SimpleDateFormat to achieve the result:
val date = Date(timeInSec)
val formattedDate = SimpleDateFormat("yyyy-MM-dd", Locale("IN")).format(date)
for details click here.
OR
Use Calendar to do it for you:
val dateObject = Date(timeInMillis)
val calendarInstance = Calendar.getInstance()
calendarInstance.time = dateObject
val date = "${calendarInstance.get(Calendar.YEAR)}-${calendarInstance.get(Calendar.MONTH)}-${calendarInstance.get(Calendar.DATE)}"
For more details check this answer.
I don't know about y'all, but I always want this stuff as a one-liner. The other answers are fine and dandy and work great, but here is it condensed to a single line. Now you can hold less lines of code in your mind :-).
Here is the one Liner:
String currentDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());