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();
}
}
Related
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
I am trying to convert String to gregoriancalendar date, it unable to convert. because, the string has different format. like '2015-05-22T16:28:40.317-04:00'. I have seen some of the other examples, but they are not in this time format.
I am using something like below:
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(new SimpleDateFormat("yyyy-MM-ddTHH:mm:ss-SS:zz").parse(sampleDate));
XMLGregorianCalendar calendar = DatatypeFactory.newInstance().newXMLGregorianCalendar( cal);
I even tried like this too:
gregory.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").parse(sampleDate));
If you check SimpleDateFormat doc, you will see that there's no T in the format pattern. In order to escape non-pattern characters, wrap them around single quotes ' as shown in this example (taken from the docs):
"hh 'o''clock' a, zzzz" -> 12 o'clock PM, Pacific Daylight Time
I think the proper format should be this:
String format = "yyyy-MM-dd'T'HH:mm:ss.SSSX";
// ^-^-----check these
// don't pay attention to the smiley generated above, they're arrows ;)
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(new SimpleDateFormat(format).parse(sampleDate));
XMLGregorianCalendar calendar = DatatypeFactory.newInstance().newXMLGregorianCalendar( cal);
This works as well
XMLGregorianCalendar xmlGregorianCalendar = DatatypeFactory.newInstance().newXMLGregorianCalendar("2015-05-22T16:28:40.317-04:00");
GregorianCalendar gregorianCalendar = xmlGregorianCalendar.toGregorianCalendar();
try {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-ddTHH:mm:ss-SS:zz");
//dateFormat.setTimeZone(TimeZone.getTimeZone());
Date inputDate = dateFormat.parse(inputDatetime);
GregorianCalendar c = new GregorianCalendar();
c.setTime(inputDate);
XMLGregorianCalendar outputDate = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
return outputDate;
} catch (ParseException | DatatypeConfigurationException e) {
log.error("exception: {}", e.getMessage());
return null;
}
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() );
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.
I need to process a list of Strings which may or may not be times. When I do receive a time, it will need to be converted from "HH:mm:ss" to number of milliseconds before processing:
final String unknownString = getPossibleTime();
final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
dateFormat.setLenient(false);
try {
final Date date = dateFormat.parse(unknownString);
//date.getTime() is NOT what I want here, since date is set to Jan 1 1970
final Calendar time = GregorianCalendar.getInstance();
time.setTime(date);
final Calendar calendar = GregorianCalendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, time.get(Calendar.HOUR_OF_DAY));
calendar.set(Calendar.MINUTE, time.get(Calendar.MINUTE));
calendar.set(Calendar.SECOND, time.get(Calendar.SECOND));
final long millis = calendar.getTimeInMillis();
processString(String.valueOf(millis));
}
catch (ParseException e) {
processString(unknownString);
}
This code works, but I really dislike it. The exception handling is particularly ugly. Is there a better way to accomplish this without using a library like Joda-Time?
public static long getTimeInMilliseconds(String unknownString) throws ParseException {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String dateString = dateFormat.format(Calendar.getInstance().getTime());
DateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return timeFormat.parse(dateString + " " + unknownString).getTime();
}
Handle the ParseException outside of this method however you'd like. I.e. ("No time information provided"... or "unknown time format"... etc.)
.getTime() returns the time in milliseconds. It's part of the java.util.Date API.
Why don't you first check if the input is actually of HH:mm:ss format. You can do this by trying match input to regex [0-9]?[0-9]:[0-9]?[0-9]:[0-9]?[0-9] first and if it matches then treat it as date otherwise call processString(unknownString);