Using Date instead of Timestamp - java

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.

Related

Wrong last day of month

Where is some function to get the last day of month in my service?
DateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
Date date = format.parse(stringDate);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.MONTH, 1);
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.add(Calendar.DATE, -1);
Date lastDayOfMonth = calendar.getTime();
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return sdf.format(lastDayOfMonth);
So, this method correctly works elsewhere, but in US last day is always 29 (last day - 1)
stringDate is date in format "yyyy-MM-dd"
I believe this problem is due to Day Light saving time in US.
You can change this by setting the Timezone for Calendar to different timezone.
Related question: Adding days with java.util.Calendar gives strange results
Java Date has very poor API. Instead of this I would recommend you to use Joda Time.
In Joda it would look like this:
LocalDate endOfMonth = date.dayOfMonth().withMaximumValue();
If you don't have Java 8, this is very compact with JodaTime.
import org.joda.time.DateTime;
public class SoLastDay {
public DateTime lastDay(final String yyyy_MM_dd) {
DateTime givenDate = new DateTime(yyyy_MM_dd);
return givenDate.dayOfMonth().withMaximumValue();
}
}
And a small test...
#Test
public void testLastDay() throws Exception {
SoLastDay soLastDay = new SoLastDay();
String date1 = "2015-01-27";
System.out.printf("Date %s becomes %s.\n", date1, soLastDay.lastDay(date1).toString("yyyy-MM-dd"));
String date2 = "2015-02-02";
System.out.printf("Date %s becomes %s.\n", date2, soLastDay.lastDay(date2).toString("yyyy-MM-dd"));
}
And the test results:
Date 2015-01-27 becomes 2015-01-31.
Date 2015-02-02 becomes 2015-02-28.
If you do have Java 8, you might use code like this:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
public class SoLastDayJava8 {
static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
public LocalDate lastDay(final String yyyy_MM_dd) {
LocalDate givenDate = LocalDate.parse(yyyy_MM_dd, formatter);
return givenDate.with(TemporalAdjusters.lastDayOfMonth());
}
}
The test code changes just a bit.
public class SoLastDayJava8Test {
#Test
public void testLastDay() throws Exception {
SoLastDayJava8 soLastDay = new SoLastDayJava8();
String date1 = "2015-01-27";
System.out.printf("Date %s becomes %s.\n", date1, soLastDay.lastDay(date1));
String date2 = "2015-02-02";
System.out.printf("Date %s becomes %s.\n", date2, soLastDay.lastDay(date2));
}
}
But the results are the same.
Date 2015-01-27 becomes 2015-01-31.
Date 2015-02-02 becomes 2015-02-28.
You are messing with the TimeZones.
When you execute Date date = format.parse(stringDate); you are creating a Date object with the TimeZone of the DateFormat object. Theoretically if the TimeZone is the same for all your DateFormat and Calendar objects, you should be fine. Check if they are coherent with the getTimeZone() method.
If the TimeZone of the first DateFormat is wrong (e.g. is your TimeZone or UTC or GMT), you'll get a UTC-008 conversion in the second TimeZone (and in the Calendar) resulting in the missing day since you start from midnight.
Judging from your code is the stringDate itself that has been wrongly converted somewhere else...

Java Get One Day Before Specific Date

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() );

Processing Java Strings and Dates

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);

Calendar date to yyyy-MM-dd format in java

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());

Current Date & Time in Java

I want the current date and time in the following format :
Date :YYYYMMDD
Time : HHMMSS
I tried the following
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
//get current date time with Date()
Date date = new Date();
System.out.println(dateFormat.format(date));
//get current date time with Calendar()
Calendar cal = Calendar.getInstance();
System.out.println(new Date().getTime());
By this I am getting the desired date output but the time is coming in this way 1341837848290.
The expected is HHMMSS.
Use format()
System.out.println(new SimpleDateFormat("HH:mm:SS").format(new Date()));
Date instance doesn't have any property to hold custom format, So you need to format the date instance to String with your custom format HH:mm:SS (See API doc for more detail)
See
IDEOne demo
try this
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
//get current date time with Date()
Date date = new Date();
System.out.println(dateFormat.format(date));
//get current date time with Calendar()
DateFormat timeFormat = new SimpleDateFormat("HHmmss");
Date d=new Date();
System.out.println(timeFormat.format(d);
Did you check out the joda-time library? Link here
With joda-time, you could easily call new DateTime(), call toString() on it and have this output, which may be more what you want:
public static void main(final String[] args) {
final DateTime d = new DateTime();
System.out.println(d.toString());
}
Output: 2012-07-09T14:54:13.366+02:00
Joda-Time is very powerful on the plus side. Of course, this is an extra lib you need to include, and if this is not possible or desired, another approach would probably be better.
I tried this:
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HHmmss");
Date date = Calendar.getInstance().getTime();
System.out.println(sdf.format(date));
Yields:
20120709 145518
First section is the date (20120709), the second section is the time(145518).
It seems that you have been using the wrong notation. I would recommend you take a look here for full details.
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd HH:mm:SS");
//get current date time with Date()
Date date = new Date();
System.out.println(dateFormat.format(date));
for more formatting refer API Doc

Categories

Resources