I am trying to get records from a database and I use java.util.date and java.util.calendar, to retrieve records inserted in previous 5 minutes from now I compute the interval using java.util calendar however when both dates start and end are parsed, I am not able to find rows in the timespan I am looking for, any advise to remediate the concern?
Date d = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(d);
cal.add(Calendar.MINUTE, -5);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
// SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
d = cal.getTime();
String stdate = sdf.format(d);
//System.out.println("start date" + stdate);
// process end date
Date dd = new Date();
Calendar call = Calendar.getInstance();
call.setTime(dd);
call.add(Calendar.MINUTE, -0);
dd = call.getTime();
String eddate = sdf.format(dd);
SimpleDateFormat sdft=new SimpleDateFormat("yyyyMMddHHmmssSSS");
//SimpleDateFormat sdft=new SimpleDateFormat("yyyyMMdd");
String stabledate=sdf.format(new Date());
List<customers> listofcustomers= customerepo.findAllByTscsstatusAndDateBetween("ACTIVE",sdf.parse(startdate),sdf.parse(enddate));e here
tl;dr
myPreparedStatement.setObject(
…
,
OffsetDateTime
.now( ZoneOffset.UTC )
.minusMinutes( 5 )
)
Avoid legacy date-time classes
Date & Calendar classes were years ago supplanted by the modern java.time classes defined in JSR 310.
java.time
Capture the current moment.
Instant instant = Instant.now() ;
Determine the moment five minutes ago.
Duration d = Duration.ofMinutes( 5 ) ;
Instant fiveMinutesAgo = instant.minus( d ) ;
Your database column must be of a type akin to the SQL-standard type TIMESTAMP WITH TIME ZONE.
Convert our Instant object for use with SQL.
OffsetDateTime odt = fiveMinutesAgo.atOffset( ZoneOffset.UTC ) ;
Write SQL like this:
SELECT *
FROM event_
WHERE when_ !< ?
;
Pass our OffsetDateTime object to fill-in the placeholder.
myPreparedStatement.setObject( 1 , odt ) ;
Retrieval.
OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;
Related
I want to convert this string "2022-01-13 14:33:07.996" to java sql date. I have read the answers and I have converted the string to java util date and then to java sql date. I just don't know how to get the full date in java sql date format
String dateStart = "2022-01-13 14:33:07.996";
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date1 = dateFormat.parse(dateStart);
java.util.Date utilDate = date1;
java.sql.Date sqlDate = new java.sql.Date(date1.getTime());
System.out.println(sqlDate);
in out put i get this
2022-01-13
but I want something like this 2022-01-13 14:33:07.996 in java sql date format
tl;dr
To write date-time values to a database, use appropriate objects, not text. For a date-only value, use LocalDate.
myPreparedStatement
.setObject(
… ,
LocalDateTime
.parse( "2022-01-13 14:33:07.996".replace( " " , "T" ) )
.toLocalDate()
)
Avoid legacy date-time classes
You are using terrible date-time classes that were years ago supplanted by the modern java.time classes defined in JSR 310.
Date-only
You said:
2022-01-13 14:33:07.996 in java sql date format
That is a contradiction. A java.sql.Date object represents a date-only, not a date with time-of-day.
java.time.LocalDateTime
Parse your input string as a LocalDateTime because it lacks any indicator of time zone or offset. Replace the SPACE in the middle with a T to comply with the ISO 8601 standard.
String input = "2022-01-13 14:33:07.996".replace( " " , "T" ) ;
LocalDateTime ldt = LocalDateTime.parse( input ) ;
java.time.LocalDate
Extract the date portion.
LocalDate ld = ldt.toLocalDate() ;
Database access
Write to database.
myPreparedStatement.setObject( … , ld ) ;
Retrieve from database.
LocalDate ld = myResultSet.getObject( … , LocalDate.class ) ;
These matters have been covered many many times already on Stack Overflow. Search to learn more.
No matter what I do its not working. I want to have it in dd/mm/yyyy I have tried and unable to get it done.Tried with JAVA 8 api of Instant localdate localtime localdatetime too.
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date date = dateFormat.parse("23/09/2007");
long time = date.getTime();
Timestamp ts = new Timestamp(time);
System.out.println(ts);
Prints like this 2007-09-23 00:00:00.0;
TimeStamp has its own format, so you need to format it as per your needs
Try,
SimpleDateFormat f = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date date = f.parse("23/12/2007 00:00:00");
String strDate = f.format(date);
System.out.println("Current Date = "+strDate);
java.time
You are using terrible date-time classes that were years ago supplanted by the modern java.time classes.
➥ Never use java.util.Date, java.sql.Date, nor java.sql.Timestamp.
For a date only, without time-of-day and without time zone, use LocalDate.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ;
String input = "23/09/2007" ;
LocalDate ld = LocalDate.parse( input , f ) ;
Generate text in standard ISO 8601 format.
String output = ld.toString() ;
Generate text in that same custom format.
String output = ld.format( f ) ;
How can i put 01 in date but not the exact date today in SimpleDateFormat
when I use
SimpleDateFormat day= new SimpleDateFormat("dd");
the it gives me the exact date today.. so how can i put my specific date for this
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
String NOW = (sdf.format(new java.util.Date()));
SimpleDateFormat month = new SimpleDateFormat("MM");
String MONTH = (month.format(new java.util.Date()));
SimpleDateFormat year = new SimpleDateFormat("yyyy");
String YEAR = (year.format(new java.util.Date()));
String PAST = ((MONTH)+"-"+(1)+"-"+(YEAR));
the ((MONTH)+"-"+(1)+"-"+(YEAR)); returns 1 but it should be 01 but when I run it it turn into 1 only
tl;dr
YearMonth
.now(
ZoneId.of( "America/Montreal" )
)
.atDay( 1 )
.format(
DateTimeFormatter.ofPattern( "MM-dd-uuuu" )
)
java.time
The modern approach uses the java.time classes. Never use the terrible legacy classes such as Calendar and SimpleDateFormat.
Get the current year and month.
YearMonth ym = YearMonth.now() ;
Get the first day of that month.
LocalDate ld = ym.atDay( 1 ) ;
Specify you desired formatting pattern.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM-dd-uuuu" ) ;
String output = ld.format( f ) ;
If you want to create a Date object out of a string representation of a date, then you could use parse(String source) method of SimpleDateFormat.
For example:
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
Date date = sdf.parse("09-01-2018");
Then, as you previosly showed, if you want to format a Date object to a string in a specific format, just invoke:
sdf.format(date).
Note: Be aware that sdf.parse(String source) could throw a ParseException if the string is not a valid date.
I need to pass in a Date object into a service which my API is calling. I have the info on the day, month, and year for the Date but also need a timestamp. The service is expecting it in this format:
<date>2015-04-01T00:00:00-05:00</date>
How can I add something to the Date to get this format?
Never use java.util.Date. Supplanted by java.time.Instant.
Get your date portion.
LocalDate ld = LocalDate.of( 2015 , 4 , 1 ) ;
Or use the readable Month enum.
LocalDate ld = LocalDate.of( 2015 , Month.APRIL , 1 ) ;
Get the time of day when the day starts in some particular time zone. Do not assume the day starts at 00:00:00, may be some other time such as 01:00:00. Let java.time figure that out for you.
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = ld.atStartOfDay( z ) ;
Generate a string in your desired format, a standard ISO 8601 format.
DateTimeFormatter f = DateTimeFormatter.ISO_OFFSET_DATE_TIME ;
String output = zdt.format( f ) ;
To see that moment in UTC, extract a Instant.
Instant instant = zdt.toInstant() ;
Conversion
If you must inter-operate with old code not yet updated for java.time, you can call new conversion methods added to the old classes. These include Date::from( Instant ).
java.util.Date d = java.util.Date.from( instant ) ;
Going the other direction.
Instant instant = d.toInstant() ;
Get back to a time zone other than UTC.
ZonedDateTime zdt = instant.atZone( ZoneId.of( "Pacific/Auckland" ) ) ; // Same moment, different wall-clock time.
Working with dates in Java is an ugly mess, always has been. Date class is mostly deprecated now. I am using LocalDateTime where you can construct it by calling year, month, day, hour, minute, and seconds. Here is what I could come up with:
LocalDateTime ldt = LocalDateTime.of(1997, Month.SEPTEMBER, 2, 1, 23, 0);
ZonedDateTime systemTime = ldt.atZone(ZoneId.systemDefault());
DateTimeFormatter formatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME; //Basil's idea
System.out.println(systemTime.format(formatter));
Output:
1997-09-02T01:23:00-05:00
You could use SimpleDateFormat for this.
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
dateFormat.format(new Date());
I try to parse a date from a string but when I print it, it shows a bad date. My code:
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.text.SimpleDateFormat;
public class Main {
public static void main(String args[]) {
String some_date = "2017-12-31";
Calendar cal_aux = GregorianCalendar.getInstance();
System.out.println("set calendar: " + Integer.parseInt(some_date.substring(0, 4))
+ Integer.parseInt(some_date.substring(5, 7))
+ Integer.parseInt(some_date.substring(8, 10)));
cal_aux.set(Integer.parseInt(some_date.substring(0, 4)),
Integer.parseInt(some_date.substring(5, 7)),
Integer.parseInt(some_date.substring(8, 10)));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("sdf calendar: " + sdf.format(cal_aux.getTime()));
}
}
Console output:
set calendar: 20171231
sdf calendar: 2018-01-31 12:51:02
Why when I use the simple date format I'm getting 2018 instead of 2017?
Avoid the legacy date-time classes now supplanted by java.time classes. The problematic legacy classes have many design faults. One such fault is counting months as 0-11 rather than 1-12. This crazy counting is breaking your code.
Do not manipulate date-time values as strings. Use objects.
For that date-only value use LocalDate.
LocalDate ld = LocalDate.parse( "2017-12-31" ) ; // Or LocalDate.now() for today's date.
Generate a String by using a DateTimeFormatter.
String output = ld.format( DateTimeFormatter.BASIC_ISO_DATE ) ;
20171231
Assign a time-of-day if desired.
LocalTime lt = LocalTime.of( 6 , 15 ) ;
LocalDateTime ltd = LocalDateTime.of( ld , lt ) ;
Apply a time zone if you want an actual moment, a specific point on the timeline.
ZoneId z = ZoneId.of( "Africa/Casablanca" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;
First, you set wrong date because the month range is 0-11. When you set 12 in month field, is january 2018 instead december 2017.
Second, you can simplify your program parsing the input string to formatted date and parsing this date to output formatted string. Here is an example:
String input = "20171231";
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyyMMdd");
SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
System.out.println(outputFormat.format(inputFormat.parse(input)));
} catch (ParseException e) {
// Log error
}