I would like to achieve below:
I have date in string format as e.g. "2015-05-12 15:15:24",
I would like to convert it to sql date in the format "dd-MMM-yy".
However, this is not working. below is the code snippet:
String rawDate="2015-05-12 15:15:24";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date =format.parse(rawDate);
Date sqlDate = new java.sql.Date(date.getTime());
SimpleDateFormat changedFormat = new SimpleDateFormat("dd-MMM-yy");
Date date2=changedFormat.parse(changedFormat.format(sqlDate));
Date sqlDate2 = new java.sql.Date(date2.getTime());
System.out.println("sqlDate : "+sqlDate +" :::::: Date2 : "+date2+" :::: sqlDate2 "+sqlDate2);ow here is the Test : "+sqlDate2);
The output of the program is :
sqlDate : 2015-05-12 :::::: Date2 : Tue May 12 00:00:00 BST 2015 :::: sqlDate2 2015-05-12
The aim was to get date in the format of 12-May-15 java.sql format, but May is not being translated into alphabet month rather its printed as number.
am I missing anything. any help would be appreciated.
tl;dr
Use objects, not strings, to communicate with database.
Use only java.time classes, never java.util.Date, Calendar, or java.sql.Date classes.
myPreparedStatement.setObject( // Use smart objects, not dumb strings.
… , // Specify which placeholder `?` in you SQL.
LocalDateTime.parse( // Parse input string lacking any zone or offset as a `LocalDateTime` object. *NOT* a moment, just a vague idea about *potential* moments.
"2015-05-12 15:15:24".replace( " " , "T" ) // Alter your input string to comply with ISO 8601 standard format, with `T` in the middle.
) // Returns a `LocalDateTime` object.
.atOffset( // Apply an offset-from-UTC to determine a moment, a specific point on the timeline.
ZoneOffset.UTC // Apply UTC if the input string was intended to be a moment in UTC.
) // Returns a `OffsetDateTime` object.
.toLocalDate() // Extract a date-only value, a `LocalDate` object from the date-with-time `OffsetDateTime` object.
)
Details
convert it to sql date in the format "dd-MMM-yy"
There is no such SQL-standard format. SQL-standard format for a date is the same as ISO 8601 standard format: YYYY-MM-DD.
java.time
You are using terrible old classes that were supplanted years ago by the modern java.time classes.
LocalDateTime
Your input string lacks any indicator of time zone or offset-from-UTC. So parse as a LocalDateTime.
The java.time classes use standard ISO 8601 format by default when parsing and generating strings. Your input string is nearly compliant with the standard. Just replace the SPACE in the middle with a T.
String input = "2015-05-12 15:15:24".replace( " " , "T" ) ;
Parse.
LocalDateTime ldt = LocalDateTime.parse( input ) ;
OffsetDateTime
A LocalDateTime does not represent a moment. It represents potential moments along a span of about 26-27 hours, the range of time zones around the globe. If you know the intended time zone, apply a ZoneId to get a ZonedDateTime object. If you know only a mere offset rather than a zone, apply a ZoneOffset to get a OffsetDateTime object. I will assume your value is intended to represent a moment in UTC, in other words, an offset-from-UTC of zero.
OffsetDateTime odt = ldt.atOffset( Offset.UTC ) ;
Smart objects, not dumb strings
You should use class types appropriate to your SQL data types to exchange data with your database. Use smart objects, not dumb strings.
As of JDBC 4.2, we can directly exchange java.time objects.
myPreparedStatement.setObject( … , odt ) ;
Retrieval.
OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;
LocalDate
You care only about the date, not the time-of-day. So extract a LocalDate object.
LocalDate ld = odt.toLocalDate() ;
Submit to your database.
myPreparedStatement.setObject( … , ld ) ;
Retrieval.
LocalDate ld = myPreparedStatement.getObject( … , LocalDate.class ) ;
Complete example
Here is a complete example app, in a single .java.
Using the H2 Database Engine. We specify an in-memory database, never persisted to storage, as this is just a demo.
package com.basilbourque.example;
import java.sql.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.UUID;
public class DateIntoDatabase {
public static void main ( String[] args ) {
DateIntoDatabase app = new DateIntoDatabase();
app.doIt();
}
private void doIt () {
try {
Class.forName( "org.h2.Driver" );
} catch ( ClassNotFoundException e ) {
e.printStackTrace();
}
try (
Connection conn = DriverManager.getConnection( "jdbc:h2:mem:date_into_db_example_" ) ;
Statement stmt = conn.createStatement() ;
) {
String sql = "CREATE TABLE event_ (\n" +
" id_ UUID DEFAULT random_uuid() PRIMARY KEY ,\n" +
" name_ VARCHAR NOT NULL ,\n" +
" when_ DATE NOT NULL\n" +
") ; ";
System.out.println( sql );
stmt.execute( sql );
// Insert row.
sql = "INSERT INTO event_ ( name_ , when_ ) " + "VALUES ( ? , ? ) ;";
try ( PreparedStatement preparedStatement = conn.prepareStatement( sql ) ; ) {
String name = "whatever";
LocalDate ld = LocalDateTime.parse( "2015-05-12 15:15:24".replace( " " , "T" ) ).atOffset( ZoneOffset.UTC ).toLocalDate();
preparedStatement.setString( 1 , name );
preparedStatement.setObject( 2 , ld );
preparedStatement.executeUpdate();
}
// Query all.
sql = "SELECT * FROM event_ ;";
try ( ResultSet rs = stmt.executeQuery( sql ) ; ) {
while ( rs.next() ) {
//Retrieve by column name
UUID id = ( UUID ) rs.getObject( "id_" ); // Cast the `Object` object to UUID if your driver does not support JDBC 4.2 and its ability to pass the expected return type for type-safety.
String name = rs.getString( "name_" );
LocalDate ld = rs.getObject( "when_" , LocalDate.class );
//Display values
System.out.println( "id: " + id + " | name: " + name + " | when: " + ld );
}
}
} catch ( SQLException e ) {
e.printStackTrace();
}
}
}
When run:
id: 0a4fd38c-7d4e-4049-bc21-e349582c8bc5 | name: whatever | when: 2015-05-12
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
You computed it, but never printed it:
String rawDate = "2015-05-12 15:15:24";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = format.parse(rawDate);
java.sql.Date sqlDate = new java.sql.Date(date.getTime());
SimpleDateFormat changedFormat = new SimpleDateFormat("dd-MMM-yy");
System.out.println("Formatted Date: " + changedFormat.format(sqlDate));
You have in your code the date in the format you want, but you are assing into a other object type date .
change this :
Date date2=changedFormat.parse(changedFormat.format(sqlDate));
Date sqlDate2 = new java.sql.Date(date2.getTime());
to this : String dateformat =(changedFormat.format(sqlDate));
you can pass the value from the string yo your object date. but if you print the var date you don´t print in the format you want, and this is becouse :
Date does not store any format into itself.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
Currently, I am trying to add my datetime into SQL from JavaFX GUI, but I keep getting the number format exception error. The Datetime format is yyyy-MM-dd HH:mm:ss, but I can also add in just like 12:30 etc.
private void doAdd() {
//Input from the user in GUI format
int EntryID = Integer.valueOf(tfEntryID.getText());
String PersonName = tfPersonName.getText();
int CheckInTime = Integer.parseInt(tfCheckInTime.getText());
String CheckTime = String.valueOf(CheckInTime);
Date date = new Date(CheckInTime);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") ;
String currentDateTime = format.format(date);
String insertSql = String.format("INSERT INTO entry_records(
EntryID, PersonName, CheckTime) VALUES ('%s', '%s', %s)",
EntryID , PersonName ,currentDateTime );
int rowsAdded = DBUtil.execSQL(insertSql);
if (rowsAdded == 1) {
System.out.println("STATUS: ADD Entry Record (ID" + EntryID + ") Successful!");
} else {
System.out.println("Adding failed!");
}
}
Never use Date and SimpleDateFormat classes. They are terribly flawed in design. They were years ago supplanted by the modern java.time classes defined in JSR 310.
With JDBC 4.2 and later, you can exchange date-time objects with your database use java.time objects. No need for string manipulations.
Parse your input string into a LocalDateTime object if you have only date and time-of-day and intend to ignore time zones.
DateTimeFormatter f = DateTimeFormatter.ofPattern( … ) ;
LocalDateTime ldt = LocalDateTime.parse( input , f ) ;
Write that value to your database using a PreparedStatement to avoid the security risks of SQL-injection.
myPreparedStatement.setObject( … , ldt ) ;
Retrieval.
LocalDateTime ldt = myResultSet.getObject( … , LocalDateTime.class ) ;
The LocalDateTime class is appropriate to a database column of a type akin to SQL-standard TIMESTAMP WITHOUT TIME ZONE. These types are inherently ambiguous as they both purposely lack the context of a time zone or offset-from-UTC. So they cannot represent a moment, are not a specific point on the timeline.
To represent a moment, use classes Instant/OffsetDateTime/ZonedDateTime, with OffsetDateTime being appropriate to SQL exchange. For database column type, use a type akin to the SQL-standard TIMESTAMP WITH TIME ZONE.
All of this has been covered many times already on Stack Overflow. Search to learn more.
I'm struggling to find the error in my code here. paytotal is coming out 0 when it should have a number.
firstDayOfPaycheck is the date Oct. 23rd 2020.
lastDayOfPaycheck is the date Nov. 6 2020.
My Simple date format sdf is "MMM dd, yyyy".
string dateInQuestion passed into runPayroll is "Oct. 31, 2020" which came originally from the same sdf as above.
I'm new to java and haven't dealt with manipulating the calendar like this. It feels like the code below should work.
private void runPayroll(String dateInQuestion, long payForTask){
c.setTime(firstDayOfPaycheck);
//loop through days of paycheck. number from time.compareTo(time2) is negative while time is before time2
while(c.getTime().compareTo(lastDayOfPaycheck)<=0){
if(dateInQuestion != null) {
Date questionDate = sdf.parse(dateInQuestion, new ParsePosition(0));
if (c.getTime().compareTo(questionDate) == 0) {
payTotal += payForTask;
}
}
c.add(Calendar.DAY_OF_YEAR, 1);
}
} //ran inside the query to get the total pay
private void buildPayrollDash(){
String strPayrollAmt = "$" + payTotal;
String startDate = sdf.format(firstDayOfPaycheck);
String trimmedStart = startDate.split(",")[0]; //cuts out the year in the date
String endDate = sdf.format(lastDayOfPaycheck);
String trimmedEnd = endDate.split(",")[0];
int holdBack = sharedPreferences.getInt("payroll holdback", 7);
c.setTime(lastDayOfPaycheck);
c.add(Calendar.DAY_OF_YEAR, holdBack);
String payDate = sdf.format(c.getTime());
String trimmedPaydate = payDate.split(",")[0];
tvPayrollTimefame.setText("Pay from " + trimmedStart + " - " + trimmedEnd);
tvPayrollAmount.setText(strPayrollAmt + " due " + trimmedPaydate);
I'm struggling to find the error in my code here.
You are using terrible date-time classes that were supplanted years ago by the modern java.time classes. Never use Date, Calendar, GregorianCalendar, or their relatives.
firstDayOfPaycheck is the date Oct. 23rd 2020.
Use LocalDate to represent a date without time-of-day and without time zone.
LocalDate firstDayOfPayPeriod = LocalDate.of( 2020 , Month.OCTOBER , 23 ) ;
lastDayOfPaycheck is the date Nov. 6 2020.
You'll find date-time handling much easier if you define your spans-of-time using the Half-Open approach. The beginning is inclusive while the ending is exclusive. So instead of focusing on the last day of the pay period, focus on the first day of the following period.
LocalDate firstDayOfSuccessivePayPeriod = LocalDate.of( 2020 , 11 , 7 ) ;
Tip: You can represent the date range of the pay period as a LocalDateRange object if you add the ThreeTen-Extra library to your Java project.
My Simple date format sdf is "MMM dd, yyyy".
You should not be mixing business logic with localization code. Custom formatting of date-times should only be done for presentation to the user.
When exchanging date-time values textually as data, use the standard ISO 8601 formats. For a date-only value, the standard format is YYYY-MM-DD. The java.time use ISO 8601 formats by default, so no need to specify any formatting pattern.
string dateInQuestion passed into runPayroll is "Oct. 31, 2020" which came originally from the same sdf as above.
LocalDate dateInQuestion = LocalDate.parse( "2020-10-31" ) ;
If you must accommodate an input of formatted date string rather than standard ISO 8601 format, use DateTimeFormatter. This has been covered many many times already on Stack Overflow, so search for more info.
And rather than check for valid data later, check your inputs early in your code. “Fail fast” is the saying.
try
{
LocalDate dateInQuestion = LocalDate.parse( "2020-10-31" );
}
catch ( DateTimeParseException e )
{
// … Handle faulty input.
e.printStackTrace();
}
I'm new to java and haven't dealt with manipulating the calendar like this. It feels like the code below should work.
Your code will be much simpler when using java.time. For one thing, the java.time classes offer convenient isBefore, isAfter, and isEqual methods, so no need for clumsy compareTo calls.
LocalDate firstDayOfPayPeriod = LocalDate.of( 2020 , Month.OCTOBER , 23 );
LocalDate firstDayOfSuccessivePayPeriod = LocalDate.of( 2020 , 11 , 7 );
String input = "2020-10-31";
LocalDate dateInQuestion = null;
try
{
dateInQuestion = LocalDate.parse( input );
}
catch ( DateTimeParseException e )
{
// Handle faulty input.
e.printStackTrace();
}
// Validate dates.
Objects.requireNonNull( firstDayOfPayPeriod );
Objects.requireNonNull( firstDayOfSuccessivePayPeriod );
Objects.requireNonNull( dateInQuestion );
if ( ! firstDayOfPayPeriod.isBefore( firstDayOfSuccessivePayPeriod ) )
{
throw new IllegalStateException( "…" );
}
if ( dateInQuestion.isBefore( firstDayOfPayPeriod ) )
{
throw new IllegalStateException( "…" );
}
if ( ! dateInQuestion.isBefore( firstDayOfSuccessivePayPeriod ) )
{
throw new IllegalStateException( "…" );
}
long payPerDay = 100;
long partialPay = 0;
LocalDate localDate = firstDayOfPayPeriod;
while ( localDate.isBefore( firstDayOfSuccessivePayPeriod ) )
{
if ( localDate.isBefore( dateInQuestion ) )
{
partialPay = ( partialPay + payPerDay );
}
// Set up the next loop.
// Notice that java.time uses immutable objects. So we generate a new object based on another’s values rather than alter (mutate) the original.
localDate = localDate.plusDays( 1 ); // Increment to next date.
}
System.out.println( "Partial pay earned from firstDayOfPayPeriod " + firstDayOfPayPeriod + " to dateInQuestion " + dateInQuestion + " is " + partialPay );
See this code run live on IdeOne.com.
Partial pay earned from firstDayOfPayPeriod 2020-10-23 to dateInQuestion 2020-10-31 is 800
With more experience in programming Java, you may want to do this kind of work using streams. See LocalDate::datesUntil.
By the way, if you want to skip weekends, add something like this:
Set< DayOfWeek > weekend = EnumSet.of( DayOfWeek.SATURDAY , DayOfWeek.SUNDAY ) ;
…
if ( weekend.contains( localDate.getDayOfWeek() ) ) { … }
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 brought some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android (26+) bundle implementations of the java.time classes.
For earlier Android (<26), a process known as API desugaring brings a subset of the java.time functionality not originally built into Android.
If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. See How to use ThreeTenABP….
I am having a problem using the ResultSet.getDate() method. I have a date field in MySQL and when I try to get the value, the date obtained is today's date instead of the date in the table specified. I don't know what is causing this error, I have searched other posts, but other errors with getDate() were different, like parsing or data mismatch errors or other kinds of errors. It could be an error due to time zone, because the values of the dates are from yesterday, but there's one row with date of two days ago and it's also returning today's date.
Here's the code:
package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.joda.time.LocalDate;
import model.Paciente;
import teste.ConnectionFactory;
public class PacienteDao {
// a conexão com o banco de dados
private Connection connection;
public PacienteDao() {
this.connection = new ConnectionFactory().getConnection();
}
public void adiciona(Paciente paciente) {
String sql = "insert into paciente" +
" (nome_paciente,cpf_paciente,rg_paciente,data_nasc)" +
"values (?,?,?,?)";
try {
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString(1, paciente.getNome_paciente());
stmt.setString(2, paciente.getCpf());
stmt.setString(3, paciente.getRg());
java.sql.Date data_nasc = new java.sql.Date(paciente.getData_nasc().toDate().getTime());
stmt.setDate(4, data_nasc);
stmt.execute();
stmt.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public List<Paciente> listaPacientes() {
List<Paciente> pacientes = new ArrayList<Paciente>();
try {
PreparedStatement stmt = this.connection.prepareStatement("select * from paciente");
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
Paciente paciente = new Paciente();
paciente.setId_paciente(rs.getInt("id_paciente"));
paciente.setNome_paciente(rs.getString("nome_paciente"));
paciente.setCpf(rs.getString("cpf_paciente"));
paciente.setRg(rs.getString("rg_paciente"));
LocalDate dt = new LocalDate();
dt.fromDateFields(rs.getDate("data_nasc"));
paciente.setData_nasc(dt);
pacientes.add(paciente);
}
rs.close();
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
return pacientes;
}
Here's the data that should be returned (CSV):
"1","Lucas","1111111111","12222222","2017-12-19"
"2","Lucas","1111111111","12222222","2017-12-20"
"3","Lucas","1111111111","12222222","2017-12-20"
"4","Leandro","2321","21232","2017-12-20"
Here's the data that is been returned (StackTrace):
Id: 1
Nome: Lucas
CPF: 1111111111
RG: 12222222
Data de Nascimento: 2017-12-21
Id: 2
Nome: Lucas
CPF: 1111111111
RG: 12222222
Data de Nascimento: 2017-12-21
Id: 3
Nome: Lucas
CPF: 1111111111
RG: 12222222
Data de Nascimento: 2017-12-21
Id: 4
Nome: Leandro
CPF: 2321
RG: 21232
Data de Nascimento: 2017-12-21
Like I said one of the rows has a date of two days ago, but it's showing today's date too, so I think isn't a time zone error.
PS: The name of the variables and methods are in Portuguese, because the application is in Portuguese too.
The problem is here
LocalDate dt = new LocalDate();
dt.fromDateFields(rs.getDate("data_nasc"));
The first statement creates a new LocalDate set to today. The second statement is a call to the static method fromDateFields, which should have been flagged as a warning by your IDE an/or compiler. This method returns a new LocalDate object, which you discarded, and does not modify dt. The above should be:
LocalDate dt = LocalDate.fromDateFields(rs.getDate("data_nasc"));
The Answer by Jim Garrison is correct. The much simpler and more intuitive code seen below would have prevented that particular mistake.
In addition, you are:
Ignoring the crucial issue of time zone in determining a date.
Using an older library from a project that recommends you move to their modern replacement classes.
tl;dr
Using java.time classes that replaced Joda-Time.
myResultSet().getObject( … , Instant.class ) // Extract a moment on the timeline in UTC, an `Instant` object.
.atZone( ZoneId.of( "Asia/Kolkata" ) ) // Adjust into a time zone, to determine a date, rendering a `ZonedDateTime` object.
.toLocalDate() // Extract a date-only object, a `LocalDate` without time-of-day and without a time zone.
Avoid legacy classes
You should not be using PreparedStatement::getDate(). Avoid all of the troublesome old date-time classes bundled with the earliest versions of Java, such as Date, Calendar, and the related java.sql types. These are entirely supplanted with the java.time classes and a JDBC 4.2 driver.
Likewise, the Joda-Time project is now in maintenance mode. Its team advises migration to the java.time which they inspired, defined, and implemented in JSR 310.
java.time
Use getObject and setObject methods.
LocalDate ld = myResultSet().getObject( … , LocalDate.class ) ; // For retrieving a standard SQL `DATE` column.
And…
myPrepatedStatement.setObject( … , ld ) ;
That code above is for a standard SQL DATE column which is a date-only value.
But it sounds like you have a moment stored, perhaps the MySQL type TIMESTAMP which seems to track with the standard SQL TIMESTAMP WITH TIME ZONE type. Any provided offset or time zone info is used to adjust the value into UTC upon submission to the database, in MySQL, with a resolution of microseconds.
So the equivalent type in Java is Instant, for a point in the timeline in UTC but with a finer resolution of nanoseconds.
Instant instant = myResultSet.getObject( … , Instant.class ) ;
And…
myPreparedStatement.setObject( … , instant ) ;
Remember that the Instant is always in UTC. But determining a date requires a time zone. For any given moment, the date varies by zone.
ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
From there extract the date-only object that seems to be your goal.
LocalDate ld = zdt.toLocalDate() ;
I'm facing this unique issue while retrieving date column values from postgres and export as a CSV using JDK 1.7 Following is a sample output
ID, Date Created, Date Modified
816271, 8/8/2013 14:35 2/2/2015 16:47
830322 13/08/2013 11:48 AM 2/2/2015 16:48
1128312 10/2/2015 16:53 10/2/2015 16:53
1129465 12/2/2015 16:23 12/2/2015 16:23
1130482 16/02/2015 4:28 PM 15/06/2015 7:01 AM
1019527 19/08/2014 4:40 AM 23/02/2015 12:14 PM
1134334 23/02/2015 8:38 AM 4/6/2015 5:16
The problem is, I see that AM/PM being appended those date values where the DAY part is greater than 12. When I look into the database I don't see any AM/PM. In my DO, I've just declared the variable as Date.
Please let me know why this inconsistent formatting happens.
thanks
Following is how I set the date into my DO.
public void setCreatedDate(Date createdDate) {
if (createdDate == null) {
this.mCreatedDate = createdDate; return;
}
this.mCreatedDate = new Date(createdDate.getTime());
}
I'm not using any formatting code at all. Even there is one, I'm not sure why it is not applied to all record
You need to understand that a date-time value stored in a database using a date-time data type has no format. What you are seeing are String representations of that date-time value generated for the convenient viewing by humans. The String is not the date-time.
So your formatting issue with "AM/PM" relates to some code generating that string outside of Postgres. You do not show us that code, so we cannot directly resolve the Question. But you can avoid the problem in the first place if you consciously work with date-time values/objects rather than Strings.
Storing date-time in Postgres
In Postgres, you should generally be using the TIMESTAMP WITH TIME ZONE data type. This type does not actually keep the time zone. Rather it has respect for the time zone, using any passed offset or time zone information accompanying data input to adjust to UTC. The result is then stored in the database. After adjustment, Postgres discards the original offset or time zone info.
Retrieving date-time from Postgres
When retrieving data (a SELECT), you may get a date-time value or you may get a String, depending on the client app (pgAdmin, psql, SQuirreL SQL Client, and such) or your database driver (JDBC and such). If getting a String, an adjustment to some time zone may have been made on your behalf, but that String is not the date-time value. If getting a date-time value, stick with that value for your work rather than converting to strings. In JDBC, that means using java.sql.Timestamp objects, for example.
Java date-time frameworks
If using Java 8 or later technology, you should make use of the new java.time package. If not possible, use the Joda-Time library. Try to avoid java.util.Date/.Calendar & java.text.SimpleDateFormat as they are troublesome and confusing.
Example
Below is a full example of extracting a java.sql.Timestamp from Postgres 9.4, then using java.time or Joda-Time to work with the value.
Data Loss with Joda-Time & java.util.Date
Note that Joda-Time (like java.util.Date) is limited to millisecond precision of fractional seconds. Postgres resolves to microseconds. So converting from Postgres to Joda-Time/java.util.Date means likely data loss. With java.time, no problem as it resolves to nanoseconds.
Code
Written in Java 8 Update 51, using the postgresql-9.4-1201.jdbc41.jar driver with Postgres 9.4.x on Mac OS X Mountain Lion.
String message = "Example of fetching Timestamp from Postgres.";
StringBuilder sql = new StringBuilder();
sql.append( "SELECT now() " + "\n" );
sql.append( ";" );
java.sql.Timestamp ts = null;
try ( Connection conn = DatabaseHelper.instance().connectionInAutoCommitMode() ;
PreparedStatement pstmt = conn.prepareStatement( sql.toString() ); ) {
try ( ResultSet rs = pstmt.executeQuery(); ) {
// Extract data from result set
int count = 0;
while ( rs.next() ) {
count ++;
ts = rs.getTimestamp( 1 );
}
}
} catch ( SQLException ex ) {
logger.error( "SQLException during: " + message + "\n" + ex );
} catch ( Exception ex ) {
logger.error( "Exception during: " + message + "\n" + ex );
}
java.sql.Timestamp
Beware of how the old Java date-time classes implicitly apply your JVM’s current default time zone. While intended to be helpful, it creates no end of confusion. The time zone seen when running this code is America/Los_Angeles which has an offset of −07:00.
String output_SqlTimestamp = ts.toString(); // Confusingly applies your JVM’s current default time zone.
java.time
Use java.time in Java 8 and later.
// If you have Java 8 or later, use the built-in java.time package.
java.time.Instant instant = ts.toInstant();
java.time.ZoneId zoneId = ZoneId.of( "America/Montreal" );
java.time.ZonedDateTime zdt = java.time.ZonedDateTime.ofInstant( instant , zoneId );
String output_UTC = instant.toString();
String output_Montréal = zdt.toString();
System.out.println( "output_SqlTimestamp: " + output_SqlTimestamp );
System.out.println( "output_UTC: " + output_UTC );
System.out.println( "output_Montréal: " + output_Montréal );
Joda-Time
Before Java 8, use Joda-Time.
// Before Java 8, use Joda-Time. (Joda-Time was the inspiration for java.time.)
// IMPORTANT: Joda-Time, like java.util.Date, is limited to milliseconds for fraction of a second. So you may experience data loss from a Postgres date-time value with microseconds.
org.joda.time.DateTime dateTimeMontréal = new org.joda.time.DateTime( ts.getTime() , DateTimeZone.forID( "America/Montreal" ) ); // WARNING: Data lost with microseconds truncated to milliseconds.
org.joda.time.DateTime dateTimeUtc = dateTimeMontréal.withZone( DateTimeZone.UTC );
String output_Joda_dateTimeMontréal = dateTimeMontréal.toString();
String output_Joda_dateTimeUtc = dateTimeUtc.toString();
System.out.println( "output_Joda_dateTimeMontréal: " + output_Joda_dateTimeMontréal );
System.out.println( "output_Joda_dateTimeUtc: " + output_Joda_dateTimeUtc );
When run.
output_SqlTimestamp: 2015-08-24 12:46:06.979144
output_UTC: 2015-08-24T18:46:06.979144Z
output_Montréal: 2015-08-24T14:46:06.979144-04:00[America/Montreal]
output_Joda_dateTimeMontréal: 2015-08-24T14:46:06.979-04:00
output_Joda_dateTimeUtc: 2015-08-24T18:46:06.979Z
I am taking in two dates as command line arguments and want to check if the first one is after the second date. the format of the date it "dd/MM/yyy".
Example: java dateCheck 01/01/2014 15/03/2014
also i will need to check if a third date hardcoded into the program is before the second date.
try {
System.out.println("Enter first date : (dd/MM/yyyy)");
BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date date1 = sdf.parse(bufferRead.readLine());
System.out.println("Enter second date : (dd/MM/yyyy)");
Date date2 = sdf.parse(bufferRead.readLine());
System.out.println(date1 + "\n" + date2);
if (date1.after(date2)) {
System.out.println("Date1 is after Date2");
} else {
System.out.println("Date2 is after Date1");
}
} catch (IOException e) {
e.printStackTrace();
}
To compare two dates :
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyy");
Date firstDate = sdf.parse("01/01/2014");
Date secondDate = sdf.parse("15/03/2014");
if(firstDate.before(secondDate)){
System.out.println("firstDate < secondDate");
}
else if(firstDate.after(secondDate)){
System.out.println("firstDate > secondDate");
}
else if(firstDate.equals(secondDate)){
System.out.println("firstDate = secondDate");
}
tl;dr
LocalDate ld1 = LocalDate.parse( "01/01/2014" , DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ) ;
LocalDate ld2 = LocalDate.parse( "15/03/2014" , DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ) ;
LocalDate ld3 = LocalDate.of( 2014 , Month.JULY , 1 ) ;
Boolean isFirstDateBeforeSecondDate = ld1.isBefore( ld2 ) ;
Boolean isThirdDateBeforeSecondDate = ld3.isBefore( ld2 ) ;
Boolean result = ( isFirstDateBeforeSecondDate && isThirdDateBeforeSecondDate ) ;
return result ;
Using java.time
The modern approach uses the java.time classes rather than the troublesome old legacy date-time classes (Date, Calendar, etc.).
The LocalDate class represents a date-only value without time-of-day and without time zone.
Define a formatting pattern to match your input strings using the DateTimeFormatter class.
String input = "15/03/2014" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" );
LocalDate ld = LocalDate.parse( input , f );
ld.toString(): 2014-03-15
To specify a fixed date, pass year, month, and dayOfMonth. For the month, you may specify a number, sanely numbered 1-12 for January-December (unlike the crazy 0-11 in the legacy classes!). Or you may choose to use the Month enum objects.
LocalDate firstOf2014 = LocalDate.of( 2014 , Month.JANUARY , 1 );
Compare using isBefore, isEqual, or isAfter methods.
Boolean isInputDateBeforeFixedDate = ld.isBefore( firstOf2014 ) ;
isInputDateBeforeFixedDate.toString(): false
ISO 8601
If possible, replace your particular date string format with the standard ISO 8601 format. That standard defines many useful practical unambiguous string formats for date-time values.
The java.time classes use the standard formats by default when parsing/generating strings. You can see examples in the code above. For a date-only value, the standard format is YYYY-MM-DD.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
Use SimpleDateFormat to convert a string to Date.
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date date1 = sdf.parse("01/01/2017");
Date has before and after methods and can be compared to each other as follows:
if(todayDate.after(historyDate) && todayDate.before(futureDate)) {
// In between
}
For an inclusive comparison:
if(!historyDate.after(todayDate) && !futureDate.before(todayDate)) {
/* historyDate <= todayDate <= futureDate */
}
To read a date and check before:
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyy");
try {
Date date1 = sdf.parse(string1);
Date date2 = sdf.parse(string2);
if(date1.before(date2)) {
// do something
}
} catch(ParseException e) {
// the format of the read dates is not the expected one
}