Java: Get month Integer from Date - java

How do I get the month as an integer from a Date object (java.util.Date)?

java.util.Date date= new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int month = cal.get(Calendar.MONTH);

java.time (Java 8)
You can also use the java.time package in Java 8 and convert your java.util.Date object to a java.time.LocalDate object and then just use the getMonthValue() method.
Date date = new Date();
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
int month = localDate.getMonthValue();
Note that month values are here given from 1 to 12 contrary to cal.get(Calendar.MONTH) in adarshr's answer which gives values from 0 to 11.
But as Basil Bourque said in the comments, the preferred way is to get a Month enum object with the LocalDate::getMonth method.

If you use Java 8 date api, you can directly get it in one line!
LocalDate today = LocalDate.now();
int month = today.getMonthValue();

Joda-Time
Alternatively, with the Joda-Time DateTime class.
//convert date to datetime
DateTime datetime = new DateTime(date);
int month = Integer.parseInt(datetime.toString("MM"))
…or…
int month = dateTime.getMonthOfYear();

tl;dr
myUtilDate.toInstant() // Convert from legacy class to modern. `Instant` is a point on the timeline in UTC.
.atZone( // Adjust from UTC to a particular time zone to determine date. Renders a `ZonedDateTime` object.
ZoneId.of( "America/Montreal" ) // Better to specify desired/expected zone explicitly than rely implicitly on the JVM’s current default time zone.
) // Returns a `ZonedDateTime` object.
.getMonthValue() // Extract a month number. Returns a `int` number.
java.time Details
The Answer by Ortomala Lokni for using java.time is correct. And you should be using java.time as it is a gigantic improvement over the old java.util.Date/.Calendar classes. See the Oracle Tutorial on java.time.
I'll add some code showing how to use java.time without regard to java.util.Date, for when you are starting out with fresh code.
Using java.time in a nutshell… An Instant is a moment on the timeline in UTC. Apply a time zone (ZoneId) to get a ZonedDateTime.
The Month class is a sophisticated enum to represent a month in general. That enum has handy methods such as getting a localized name. And rest assured that the month number in java.time is a sane one, 1-12, not the zero-based nonsense (0-11) found in java.util.Date/.Calendar.
To get the current date-time, time zone is crucial. At any moment the date is not the same around the world. Therefore the month is not the same around the world if near the ending/beginning of the month.
ZoneId zoneId = ZoneId.of( "America/Montreal" ); // Or 'ZoneOffset.UTC'.
ZonedDateTime now = ZonedDateTime.now( zoneId );
Month month = now.getMonth();
int monthNumber = month.getValue(); // Answer to the Question.
String monthName = month.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH );
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, 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
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.

If you can't use Joda time and you still live in the dark world :) ( Java 5 or lower ) you can enjoy this :
Note: Make sure your date is allready made by the format : dd/MM/YYYY
/**
Make an int Month from a date
*/
public static int getMonthInt(Date date) {
SimpleDateFormat dateFormat = new SimpleDateFormat("MM");
return Integer.parseInt(dateFormat.format(date));
}
/**
Make an int Year from a date
*/
public static int getYearInt(Date date) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy");
return Integer.parseInt(dateFormat.format(date));
}

If we use java.time.LocalDate api, we can get month number in integer in single line:
import java.time.LocalDate;
...
int currentMonthNumber = LocalDate.now().getMonthValue(); //OR
LocalDate scoringDate = LocalDate.parse("2022-07-01").getMonthValue(); //for String date
For example today's date is 29-July-2022, output will be 7.

Date mDate = new Date(System.currentTimeMillis());
mDate.getMonth() + 1
The returned value starts from 0, so you should add one to the result.

Related

How to format the week number to a desired format in H2

I want a date format with week number and year in the ISO format of yyyy-'W'ww. However, with only week function available in H2 database, I am able to get only the week number without the year. How can I format in such a way that I add a default year to it. Something like 2016-'W'ww.
Currently, I am using this function (which is definitely not the correct way)
WEEK(PARSEDATETIME(TRUNC(" + this.fieldName + "),'2016ww')
WEEK(PARSEDATETIME(TRUNC(" + this.fieldName + "),'2016-ww')
I am not able to get what else can be done. Can anyone help me here
There are several valid solutions in different libraries. However, you need to know that using the standard calendar year "y" would be wrong. Instead you have to use the year-of-weekdate (or called weekbased year) with symbol "Y" (capital letter).
Example using old Calendar-stuff:
java.sql.Date sqlDate = new java.sql.Date(2017 - 1900, 0, 1); // 2017-01-01
GregorianCalendar gcal = new GregorianCalendar();
gcal.setFirstDayOfWeek(Calendar.MONDAY);
gcal.setMinimalDaysInFirstWeek(4);
gcal.setTime(sqlDate);
SimpleDateFormat sdf = new SimpleDateFormat("YYYY-'W'ww");
System.out.println(sdf.format(gcal.getTime())); // 2016-W52
Example using Java-8:
java.sql.Date sqlDate = new java.sql.Date(2017 - 1900, 0, 1); // 2017-01-01
LocalDate ld = sqlDate.toLocalDate();
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("YYYY-'W'ww", Locale.FRANCE);
System.out.println(dtf.format(ld)); // 2016-W52
Side note: I have here chosen the locale of France to ensure the correct week configuration needed for ISO-8601.
Example using my library Time4J which is only interesting and gives a surplus value if you also plan to do some arithmetic with obtained calendar week (like plusWeeks(5) or plan to get some styled localized output):
java.sql.Date sqlDate = new java.sql.Date(2017 - 1900, 0, 1); // 2017-01-01
PlainDate value = JDBCAdapter.SQL_DATE.translate(sqlDate);
CalendarWeek cw =
CalendarWeek.of(
value.get(PlainDate.YEAR_OF_WEEKDATE),
value.get(Weekmodel.ISO.weekOfYear())
);
System.out.println(cw.toString()); // 2016-W52
tl;dr
org.threeten.extra.YearWeek // Handy class found in the ThreeTen-Extra library added to your project.
.from( // Determine the week number and the week-based year number from the passed `LocalDate` object, according to standard ISO 8601 definition of a week.
myResultSet.getObject( … , LocalDate.class ) // Produces a `LocalDate` object to pass to `YearWeek.from`.
)
.toString() // Generate a String in standard ISO 8601 format: yyyy-Www
2018-W13
Details
When you fetch your Date type from H2 as a java.sql.Date, convert to a java.time.LocalDate.
LocalDate ld = mySqlDate.toLocalDate();
You can interrogate for the ISO 8601 standard definition of a week where week # 1 contains the first Thursday of the year, and runs Monday-Sunday.
int weekNumber = ld.get( IsoFields.WEEK_OF_WEEK_BASED_YEAR ) ;
Extract the year.
int year = ld.getYear();
Assemble your standard ISO 8601 string.
String output = year + "-W" + String.format( "%02d ", weekNumber );
Even easier is to use the YearWeek class from the ThreeTen-Extra project.
String output = YearWeek.from( ld ).toString() ;
JDBC 4.2
As of JDBC 4.2 and later, you can directly exchange java.time objects with your database. No need to over use java.util or java.sql date-time classes again.
LocalDate ld = LocalDate.now( ZoneId.of( "Africa/Tunis" ) ) ; // Capture the current date as seen in the wall-clock used by the people in a certain region (a time zone).
myPreparedStatement.setObject( … , ld ) ;
And retrieval.
LocalDate ld = myResultSet.getObject( … , LocalDate.class ) ;
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, 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
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.

Date time String + TimeZone

I have a String representation of a local date time, and a Java TimeZone.
I am trying to get output in the format MM/dd/yyyy HH:mm:ssZ but I can't figure out how to create a Calendar or JodaTime object with the correct date time and timezone. How do you get a TimeZone converted to a value that can be parsed by SimpleDateFormat 'Z' or 'z'?
TimeZone tz = TimeZone.getTimeZone("America/Chicago");
String startDate = "08/14/2014 15:00:00";
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Calendar cal = Calendar.getInstance(tz);
cal.setTime(sdf.parse(startDate));
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ssZ");
and
sdfZ.format(cal.getTime())
returns
08/14/2014 15:00:00-0400
which is EST.
Is the only workaround to create a Calendar or Joda DateTime and set the individual year/month/day/hour/min values by parsing the string "08/14/2014 15:00:00" ?
Calendar getTime() - Returns a Date object representing this Calendar's time value (millisecond offset from the Epoch(01-01-1970 00:00 GMT)") irrespective of which timezone you are displaying. But hour of day in different TimeZone will be different. get(Calendar.HOUR_OF_DAY)
You should try
sdfZ.setTimeZone(tz);
tl;dr
ZonedDateTime zdt = ZonedDateTime.now( ZoneId.of( "America/Chicago" ) ) ;
String output = zdt.toInstant().toString() ;
2016-12-03T10:15:30Z
java.time
Both the java.util.Calendar class and the Joda-Time library have been supplanted by the java.time classes.
Instant
The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds.
Instant instant = Instant.now();
Call toString to generate a String in standard ISO 8601 format. For example, 2011-12-03T10:15:30Z. This format is good for serializing date-time values for data storage or exchange.
String output = instant.toString(); // Ex: 2011-12-03T10:15:30Z
Time zone
Assign a time zone.
ZoneId z = ZoneId.of( "America/Chicago" );
ZonedDateTime zdt = instant.atZone( z );
As a shortcut, you can skip over using Instant.
ZonedDateTime zdt = ZonedDateTime.now( z );
Calling toString on ZonedDateTime gets you an extended version of standard ISO 8601 format where the name of the time zone is appended in square brackets. For example, 2007-12-03T10:15:30+01:00[Europe/Paris].
String output = zdt.toString(); // Ex: 2007-12-03T10:15:30+01:00[Europe/Paris]
DateTimeFormatter
The DateTimeFormatter class has a predefined formatter constant for your desired output: DateTimeFormatter.ISO_LOCAL_DATE_TIME
String output zdt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME );
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.
With a JDBC driver complying with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings or java.sql.* classes.
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
Later versions of Android bundle implementations of the java.time classes.
For earlier Android, 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.

Comparing string date with today's date

So I have a string which is "2014-06-30 15:27" and if it is today's date it should only return "15:27" else "30/06/2014". I've already tried simpleDateFormat.parse but it didn't work very well.
holder.data.setText(mensagem.getDate());
final String stringDate = "2014-07-17 23:59";
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Date date = inputFormat.parse(stringDate);
Calendar calendarDate = Calendar.getInstance();
calendarDate.setTime(date);
Calendar midnight = Calendar.getInstance();
midnight.set(Calendar.HOUR_OF_DAY, 0);
midnight.set(Calendar.MINUTE, 0);
midnight.set(Calendar.SECOND, 0);
midnight.set(Calendar.MILLISECOND, 0);
if (calendarDate.compareTo(midnight) >= 0)
{
SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");
System.out.println(timeFormat.format(date));
}
else
{
SimpleDateFormat dateTimeForm = new SimpleDateFormat("dd/MM/yyyy HH:mm");
System.out.println(dateTimeForm.format(date));
}
LocalDateTime
First parse the string as a LocalDateTime. Replace the SPACE in the middle with T to comply with standard ISO 8601 format. The java.time classes support ISO 8601 formats by default.
LocalDateTime ldt = LocalDateTime.parse ( "2014-06-30 15:27".replace ( " " , "T" ) );
ldt.toString(): 2014-06-30T15:27
Such a value has no real meaning. The input string lacked any clue about offset-from-UTC or time zone. So we do not know if this is 3 PM in Auckland NZ or 3 PM in Québec Canada, two very different moments. You should to assign the offset or time zone indicated by your business situation. Search Stack Overflow for how to do this, focussing on classes OffsetDateTime and ZonedDateTime. I'll skip over this crucial issue for now.
LocalDate
Extract a date-only value. The LocalDate class represents a date-only value without time-of-day and without time zone.
LocalDate ld = ldt.toLocalDate();
Today
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );
Comparison
You can compare LocalDate objects by calling methods such as compareTo, equals, isEqual, isBefore, isAfter.
if( today.isEqual( ld ) ) {
return ldt.toLocalTime();
} else {
return ld;
}
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.
As the java.time library is the recommended way to use date and time. So, to compare current date with a string date you need to first convert date in string format to java.time.LocalDate :
LocalDate paresedStringDate = LocalDate.parse("2022-11-10");
After that you can get the current date using below code:
LocalDate currentDate = LocalDate.now();
And then you can compare both the current date and parsed string date to check if both are same using below code:
if (paresedStringDate.compareTo(currentDate) == 0) {
//do what you want to do here
}
Simply use the Date class...
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Date exitdate = df.parse("2019-01-17");
Date currdate = new Date();
long diff = currdate.getTime() - exitdate.getTime();
long days = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
if(days==0)
{
System.out.println("IS TRUE"+currdate.toString());
return true;
}

Get Date in Java given Week number, week day and year

Given Week of the year, the week day and the year, how can we get the Date in Java?
With Jodatime, I tried the following:
DateTime dt = new DateTime();
dt.withYear(year);
dt.withWeekOfWeekyear(weekOfYear);
dt.withDayOfWeek(weekDay);
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyMMdd");
System.out.println(dateTimeFormatter.print(dt));
But it gets the current Date!
JodaTime returns a changed copy, so do:
DateTime dt = new DateTime()
.withWeekyear(year)
.withWeekOfWeekyear(weekOfYear)
.withDayOfWeek(weekDay);
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyMMdd");
System.out.println(dateTimeFormatter.print(dt));
And this should work as expected.
The accepted answer has bug..withYear(year) should be withWeekyear(year). #Neet please update it.
You need to reassign the date afterwards!
the dt.with*() methods simply make a copy of the date.
try
DateTime dt = new DateTime();
dt = dt.withYear(year);
dt = dt.withWeekOfWeekyear(weekOfYear);
dt = dt.withDayOfWeek(weekDay);
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyMMdd");
System.out.println(dateTimeFormatter.print(dt));
We can also use this native java code using Calendar class:
SimpleDateFormat sdf = new SimpleDateFormat("MM dd yyyy");
Calendar cal = Calendar.getInstance();
cal.set(Calendar.WEEK_OF_YEAR, 23);
cal.set(Calendar.DAY_OF_WEEK, 3);
cal.set(Calendar.YEAR,2013);
System.out.println(sdf.format(cal.getTime()));
Here is a simple example of how to do it without JodaTime:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Snippet {
public static void main(String args[]) {
String year = "2013";
String week_of_year = "46";
String day_of_week = "4";
String yearweekday = year + week_of_year + day_of_week;
SimpleDateFormat sdf = new SimpleDateFormat("yyyywwu");
Date date = null;
try {
date = sdf.parse(yearweekday);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(date);
}
}
Good luck!
tl;dr
YearWeek.of( 2017 , 1 )
.atDay( DayOfWeek.TUESDAY )
.format( DateTimeFormatter.ofPattern( "uuMMdd" ) )
“Week” ambiguous
The word 'week' is ambiguous. Do you mean week number 1 contains January 1? Or week number 1 contains the first of a particular day of year such as Sunday or Monday?
Or do you mean a standard ISO 8601 week? To quote from YearWeek doc:
ISO-8601 defines the week as always starting with Monday. The first week is the week which contains the first Thursday of the calendar year. As such, the week-based-year used in this class does not align with the calendar year.
java.time
The modern approach uses the java.time classes.
The troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleTextFormat are now legacy, supplanted by the java.time classes.
The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes.
ThreeTen-Extra
The ThreeTen-Extra project extends java.time with additional functionality. This includes a handy YearWeek class, just what we need for this Question.
Specify your week-based year number and your week number.
YearWeek yw = YearWeek.of( 2017 , 1 ) ;
The LocalDate class represents a date-only value without time-of-day and without time zone.
You can ask the YearWeek object to determine the date of a day contained within its week. Specify a DayOfWeek enum object. Note that a DayOfWeek is an object rather than a mere integer or string, providing for type-safety and valid values.
LocalDate ld = yw.atDay( DayOfWeek.TUESDAY ) ;
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.
java.time
The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
Also, quoted below is a notice from the home page of Joda-Time:
Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.
Solution using java.time, the modern Date-Time API:
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.WeekFields;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
// Test
int weekNumber = 34;
int year = 2021;
System.out.println(getLocalDate(weekNumber, DayOfWeek.TUESDAY, year, Locale.UK));
System.out.println(getLocalDate(weekNumber, DayOfWeek.TUESDAY, year, Locale.US));
System.out.println(getLocalDate(weekNumber, DayOfWeek.SUNDAY, year, Locale.UK));
System.out.println(getLocalDate(weekNumber, DayOfWeek.SUNDAY, year, Locale.US));
}
static LocalDate getLocalDate(int weekNumber, DayOfWeek dow, int year, Locale locale) {
return LocalDate.of(year, 2, 1)
.with(dow)
.with(WeekFields.of(locale).weekOfWeekBasedYear(), weekNumber);
}
}
Output:
2021-08-24
2021-08-17
2021-08-29
2021-08-15
ONLINE DEMO
Note that the first day of the week is Locale-dependent e.g. it is Monday in the UK while Sunday in the US. As per the ISO 8601 standards, it is Monday. For comparison, check the US calendar and the UK calendar. Accordingly, the date will vary as shown in the example above.
Learn more about the modern Date-Time API from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Java Timestamp - How can I create a Timestamp with the date 23/09/2007?

How can I create a Timestamp with the date 23/09/2007?
By Timestamp, I presume you mean java.sql.Timestamp. You will notice that this class has a constructor that accepts a long argument. You can parse this using the DateFormat class:
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date date = dateFormat.parse("23/09/2007");
long time = date.getTime();
new Timestamp(time);
What about this?
java.sql.Timestamp timestamp = java.sql.Timestamp.valueOf("2007-09-23 10:10:10.0");
What do you mean timestamp? If you mean milliseconds since the Unix epoch:
GregorianCalendar cal = new GregorianCalendar(2007, 9 - 1, 23);
long millis = cal.getTimeInMillis();
If you want an actual java.sql.Timestamp object:
Timestamp ts = new Timestamp(millis);
tl;dr
java.sql.Timestamp.from (
LocalDate.of ( 2007 , 9 , 23 )
.atStartOfDay( ZoneId.of ( "America/Montreal" ) )
.toInstant()
)
java.time
Let’s update this page by showing code using the java.time framework built into Java 8 and later.
These new classes are inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project. They supplant the notoriously troublesome old date-time classes bundled with early versions of Java.
In java.time, an Instant is a moment on the timeline in UTC. A ZonedDateTime is an Instant adjusted into a time zone (ZoneId).
Time zone is crucial here. A date of September 23, 2007 cannot be translated to a moment on the timeline without applying a time zone. Consider that a new day dawns earlier in Paris than in Montréal where it is still “yesterday”.
Also, a java.sql.Timestamp represents both a date and time-of-day. So we must inject a time-of-day to go along with the date. We assume you want the first moment of the day as the time-of-day. Note that this is not always the time 00:00:00.0 because of Daylight Saving Time and possibly other anomalies.
Note that unlike the old java.util.Date class, and unlike Joda-Time, the java.time types have a resolution of nanoseconds rather than milliseconds. This matches the resolution of java.sql.Timestamp.
Note that the java.sql.Timestamp has a nasty habit of implicitly applying your JVM’s current default time zone to its date-time value when generating a string representation via its toString method. Here you see my America/Los_Angeles time zone applied. In contrast, the java.time classes are more sane, using standard ISO 8601 formats.
LocalDate d = LocalDate.of ( 2007 , 9 , 23 ) ;
ZoneId z = ZoneId.of ( "America/Montreal" ) ;
ZonedDateTime zdt = d.atStartOfDay( z ) ;
Instant instant = zdt.toInstant() ;
java.sql.Timestamp ts = java.sql.Timestamp.from ( instant ) ;
Dump to console.
System.out.println ( "d: " + d + " = zdt: " + zdt + " = instant: " + instant + " = ts: " + ts );
When run.
d: 2007-09-23 = zdt: 2007-09-23T00:00-04:00[America/Montreal] = instant: 2007-09-23T04:00:00Z = ts: 2007-09-22 21:00:00.0
By the way, as of JDBC 4.2, you can use the java.time types directly. No need for java.sql.Timestamp.
PreparedStatement.setObject
ResultSet.getObject
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 could also do the following:
// untested
Calendar cal = GregorianCalendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, 23);// I might have the wrong Calendar constant...
cal.set(Calendar.MONTH, 8);// -1 as month is zero-based
cal.set(Calendar.YEAR, 2009);
Timestamp tstamp = new Timestamp(cal.getTimeInMillis());
According to the API the constructor which would accept year, month, and so on is deprecated. Instead you should use the Constructor which accepts a long.
You could use a Calendar implementation to construct the date you want and access the time-representation as a long, for example with the getTimeInMillis method.
For completeness sake, also a solution with Joda-Time version 2.5 and its DateTime class:
new Timestamp(new DateTime(2007, 9, 23, 0, 0, DateTimeZone.forID( "America/Montreal" )).getMillis())
A more general answer would be to import java.util.Date, then when you need to set a timestamp equal to the current date, simply set it equal to new Date().

Categories