I am trying to pass values to a function as start date and end date. As of now i hard code these values where the start date would be 20210401 and end date would be 20210419. 01 is the date, 04 is the month and 2021 is the year.
I want to pass these during run time where start date would be start date of that current month, end date should be 2 days before the current date of the current month. For example if the current month is october and todays date is 15th October, 2021. Then the start date should be 20211001 and end date should be 20211013. Please suggest any code in java. It would be really helpful.
Here is a solution using LocalDate to calculate the expected dates. Note that if the current date is on the 1st or 2nd of the month the code will use current date as end date rather than doing any calculation. Feel free to change this as you see fit.
LocalDate now = LocalDate.now();
LocalDate first = now.withDayOfMonth(1);
LocalDate limit = now.withDayOfMonth(3);
LocalDate last = null;
if (now.isBefore(limit)) {
last = now;
} else {
last = now.minusDays(2);
}
I want to pass these during run time where start date would be start
date of that current month, end date should be 2 days before the
current date of the current month.
I suggest you do it using the modern date-time API as demonstrated below:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
LocalDate startDate = today.with(TemporalAdjusters.firstDayOfMonth());
LocalDate endDate = today.minusDays(2);
// Use the following optional block if your requirement is to reset the end date
// to the start date in case it falls before the start date e.g. when the
// current date is on the 1st or the 2nd day of the month
//////////////////////// Start of optional block/////////////////////
if (endDate.isBefore(startDate)) {
endDate = startDate;
}
///////////////////////// End of optional block//////////////////////
// Get the strings representing the dates in the desired format
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuuMMdd", Locale.ENGLISH);
String strStartDate = startDate.format(dtf);
String strEndDate = endDate.format(dtf);
System.out.println(strStartDate);
System.out.println(strEndDate);
}
}
Output:
20210401
20210419
Note: If your application is supposed to be used in a different timezone than that of your application's JVM, replace LocalDate with ZonedDateTime and intitialize today with ZonedDateTime.now(ZoneId zone) passing the applicable timezone e.g. ZoneId.of("Asia/Kolkata").
Learn more about the modern date-time API from Trail: Date Time.
How about using the legacy date-time API?
The legacy date-time API (java.util date-time types and their formatting API, SimpleDateFormat) are outdated and error-prone. It is recommended to stop using them completely and switch to java.time, the modern date-time API* .
* 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.
Here's a code snippet which may help. Here I am taking the local system time as the endDate and going back TWO days prior to get your startDate.
// the format you'd like to display your date as.
String pattern ="yyyyMMdd";
// this formats the date to look how you'd want it to look
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
//Get date for 2 day prior to currentDate.
long SINGLE_DAY_IN_MS = 1000 * 60 * 60 *24;
long nDaysToGoBack = 2;
//create 'startDate' variable from milliseconds as an input
Date startDate = new Date(System.currentTimeMillis()- (nDaysToGoBack*SINGLE_DAY_IN_MS));
// Set 'endDate' as your current date.
Date endDate = new Date(System.currentTimeMillis());
System.out.println();
System.out.println("Start Date: "+ simpleDateFormat.format(startDate));
System.out.println("End Date: "+ simpleDateFormat.format(endDate));
I am sure whether you want to use your current system date or whether you want to manually pass a different date into your function.
If you want to manually pass in a date (for example, 10 Jan 2021) into your function during runtime you can use the statement:
Date endDate = simpleDateFormat.parse("20210110");
and then find a way to subtract the 2 days from that endDate variable to get your startDate variable.
Related
I have a field that is defined as TIMESTAMP WITH TIME ZONE.
The value to be saved starts off as: "09-23-2019 10:03:11 pm" in the zone of US/Hawaii.
This is what I am trying to save to the DB (all of the date information plus the Zone)
The database stores time information in UTC format.
As of now, the date is being stored in the DB so that it looks like this:
DAYS
---------------------------------------------------------------------------
23-SEP-19 10.03.11.000000 PM -05:00
23-SEP-19 10.03.11.000000 PM -05:00
During the processing, it runs through this code:
dateStr: the date (as seen above)
ZoneLoc: 'US/Hawaii'
public Calendar convDateStrWithZoneTOCalendar(String dateStr,
String ZoneLoc) throws Exception {
// convert the string sent in from user (which uses AM/PM) to one that uses military time (24HR)
// it
String formattedDate = null;
DateFormat readFormat = new SimpleDateFormat(this.getPattern());
DateFormat writeFormat = new SimpleDateFormat("MM-dd-yyyy'T'HH:mm:ss'Z'");
writeFormat.setTimeZone(TimeZone.getTimeZone(ZoneLoc));
Date date = null;
date = readFormat.parse(dateStr);
formattedDate = writeFormat.format(date);
// see if you can parse the date needed WITH the TimeZone
Date d;
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy'T'HH:mm:ss'Z'");
sdf.setTimeZone(TimeZone.getTimeZone(ZoneLoc));
d = sdf.parse(formattedDate);
Calendar cal = Calendar.getInstance();
cal.setTime(d);
system.out.println(" ZONELOC VALUE " + ZoneLoc);
system.out.println(" RETURNED VALUE " + cal );
return cal;
}
The calendar info that is returned is:
ZONELOC VALUE IS US/Hawaii
RETURNED VALUE IS
java.util.GregorianCalendar[time=1577678591000,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="America/Chicago",offset=-21600000,dstSavings=3600000,useDaylight=true,transitions=235,lastRule=java.util.SimpleTimeZone[id=America/Chicago,offset=-21600000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=2,startDay=8,startDayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,endDayOfWeek=1,endTime=7200000,endTimeMode=0]],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2019,MONTH=11,WEEK_OF_YEAR=1,WEEK_OF_MONTH=5,DAY_OF_MONTH=29,DAY_OF_YEAR=363,DAY_OF_WEEK=1,DAY_OF_WEEK_IN_MONTH=5,AM_PM=1,HOUR=10,HOUR_OF_DAY=22,MINUTE=3,SECOND=11,MILLISECOND=0,ZONE_OFFSET=-21600000,DST_OFFSET=0]
It looks as though US/Hawaii is not being set in the RETURNED VALUE.
What can I do to be sure that this gets set?
After that, I can place it in the DB and see if the setting will "stick" and not revert back to America/Chicago
Update
#Patrick H - thanks for the input. I made the change with the pattern you specified and was able to save the data. It now looks like this:
2017-08-02 13:38:49 TRACE o.h.type.descriptor.sql.BasicBinder - binding parameter [26] as [TIMESTAMP] - [java.util.GregorianCalendar[time=1569294191000,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="America/Chicago",offset=-21600000,dstSavings=3600000,useDaylight=true,transitions=235,lastRule=java.util.SimpleTimeZone[id=America/Chicago,offset=-21600000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=2,startDay=8,startDayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,endDayOfWeek=1,endTime=7200000,endTimeMode=0]],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2019,MONTH=8,WEEK_OF_YEAR=39,WEEK_OF_MONTH=4,DAY_OF_MONTH=23,DAY_OF_YEAR=266,DAY_OF_WEEK=2,DAY_OF_WEEK_IN_MONTH=4,AM_PM=1,HOUR=10,HOUR_OF_DAY=22,MINUTE=3,SECOND=11,MILLISECOND=0,ZONE_OFFSET=-21600000,DST_OFFSET=3600000]]
The data in the DB looks like this:
23-SEP-19 10.03.11.000000 PM -05:00
The Zone is still America/Chicago even through US/Hawaii was specified. How can one get US/Hawaii to stick and not revert back to America/Chicago?
According to this output:
java.util.GregorianCalendar[time=1569294191000,...
The time value above (which means 1569294191000 milliseconds since unix epoch (1970-01-01T00:00Z)) is equivalent to 09-23-2019 10:03 PM in Chicago. That's because readFormat is using the system's default timezone (which is probably America/Chicago, just check the value of TimeZone.getDefault()).
To parse the input 09-23-2019 10:03:11 pm and consider it as the local time in Hawaii, you just need to set the corresponding timezone to the SimpleDateFormat instance (in this case, to readFormat, as it needs to know in what timezone the input date is - as you didn't set any, it uses the system's default). You also don't need the other formatters (writeFormat and sdf), only one formatter can be used to get the corresponding date:
SimpleDateFormat parser = new SimpleDateFormat("MM-dd-yyyy hh:mm:ss a");
// the input is in Hawaii timezone
parser.setTimeZone(TimeZone.getTimeZone("US/Hawaii"));
Date date = parser.parse("09-23-2019 10:03:11 pm");
The date above will be equivalent to 10:03 PM in Hawaii. Actually, the date itself contains just the milliseconds from the unix epoch (date.getTime() returns 1569312191000) and has no format nor any timezone information.
You can then set it to a Calendar instance (don't forget to set the calendar's timezone):
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("US/Hawaii"));
cal.setTime(date);
It's been some time since I used oracle's timestamp with timezone type, but I think that'll be enough to save the correct values. The value of calendar is:
java.util.GregorianCalendar[time=1569312191000,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="US/Hawaii",offset=-36000000,dstSavings=0,useDaylight=false,transitions=7,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2019,MONTH=8,WEEK_OF_YEAR=39,WEEK_OF_MONTH=4,DAY_OF_MONTH=23,DAY_OF_YEAR=266,DAY_OF_WEEK=2,DAY_OF_WEEK_IN_MONTH=4,AM_PM=1,HOUR=10,HOUR_OF_DAY=22,MINUTE=3,SECOND=11,MILLISECOND=0,ZONE_OFFSET=-36000000,DST_OFFSET=0]
Java new Date/Time API
The old classes (Date, Calendar and SimpleDateFormat) have lots of problems and design issues, and they're being replaced by the new APIs.
One of the main problems is how hard and confusing it is to work with different timezones.
If you're using Java 8, consider using the new java.time API. It's easier, less bugged and less error-prone than the old APIs.
If you're using Java <= 7, you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. And for Android, there's the ThreeTenABP (more on how to use it here).
The code below works for both.
The only difference is the package names (in Java 8 is java.time and in ThreeTen Backport (or Android's ThreeTenABP) is org.threeten.bp), but the classes and methods names are the same.
To parse the input 09-23-2019 10:03:11 pm you can use a DateTimeFormatter and parse it to a LocalDateTime - the input has no timezone information, so we consider only the date and time, and then we can convert it to a timezone.
// parse the input
DateTimeFormatter fmt = new DateTimeFormatterBuilder()
// parse AM/PM and am/pm
.parseCaseInsensitive()
// input pattern
.appendPattern("MM-dd-yyyy hh:mm:ss a")
// use English locale for am/pm symbols
.toFormatter(Locale.ENGLISH);
LocalDateTime dt = LocalDateTime.parse("09-23-2019 10:03:11 pm", fmt);
// convert to Hawaii timezone
ZonedDateTime hawaiiDate = dt.atZone(ZoneId.of("US/Hawaii"));
The most recent JDBC drivers have support to the new API (but only for Java 8, I guess), but if you still need to work with Calendar, you can easily convert a ZonedDateTime to it:
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("US/Hawaii"));
calendar.setTimeInMillis(hawaiiDate.toInstant().toEpochMilli());
In Java 8, you can also do:
Calendar calendar = GregorianCalendar.from(hawaiiDate);
If you need interoperability with the old Calendar and Date API's, you can use the new API internally to do the calculations and convert from/to the API's when needed.
According to SimpleDateFormat, I think your formatting string is wrong. You can also see in the returned value that the month, and day are wrong. MONTH=11,DAY_OF_MONTH=29
This is what you currently have:
23-SEP-19 10.03.11.000000 PM -05:00
I think the formatting string should be: 'dd-MMM-yy hh.mm.ss.SSSSSS a Z'
It also looks like the timezone issue could be because there is a colon inside it. The documentation for SimpleDateFormat indicates it needs to be in this format instead for a RFC 822 time zone: -0500 You may find it easier to use the General time zone component instead.
I am trying to Parse "8:30 AM" but I am getting Unparseable Date Exception.
From my UI side I am getting "8:30 AM" and "6:30 PM" kind of values but I have to convert that String into Date format and save that date in my database.
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Test {
public static void main(String[] args) {
SimpleDateFormat timingFormat = new SimpleDateFormat("h a",
Locale.US);
String dateInString = "8:30 AM";
try {
// This line throws Unparseable exception
Date date = timingFormat.parse(dateInString);
System.out.println(date);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
From Documentation
the year value of the parsed Date is 1970 with GregorianCalendar if no
year value is given from the parsing operation. The TimeZone value may
be overwritten, depending on the given pattern and the time zone value
in text.
try this
SimpleDateFormat timingFormat = new SimpleDateFormat("h a", Locale.US);
Date date = timingFormat.parse("8 AM");
System.out.println(date.toString());
Output
Thu Jan 01 08:00:00 IST 1970
UPDATE
To get today date,you can try something like this after parsing
int hours = date.getHours();
Date today = new Date();
today.setHours(hours);
System.out.println(today);
Note getHours() and setHours are deprecated methods.Its recommended to go for Calendar.You will have to set hours, minutes explicitly.
UPDATE
if input is 8:30 or so,then you will have to parse it like this
SimpleDateFormat timingFormat = new SimpleDateFormat("h:mm a", Locale.US);
Date date = timingFormat.parse("8:30 AM");
System.out.println(date.toString());
Output
Thu Jan 01 08:30:00 IST 1970
Depending on the input,you need to select which kind of format you are insterested.You can check that whether string contains : or not,based on that you can use SimpleDateFormat.
Just to Parse 8:30 AM just change the formatter above with
SimpleDateFormat timingFormat = new SimpleDateFormat("h:mm a");
Regards
The accepted answer is correct but outdated.
As mentioned, the Question has an input string which means only a time-of-day while the java.util.Date class represents both a date plus a time-of-day.
What you need is a class that represents only a time-of-day. No such class in the older versions of Java before Java 8.
java.time
The java.time framework built into Java 8 and later supplants the troublesome old java.util.Date/.Calendar classes. The new classes are inspired by the highly successful Joda-Time framework, intended as its successor, similar in concept but re-architected. Defined by JSR 310. Extended by the ThreeTen-Extra project. See the Tutorial.
LocalTime
The java.time classes include the LocalTime class. This class represents a time-of-day without any date nor time zone.
Note that for the formatter we specified a Locale using the English language to correctly identify the strings AM and PM which could vary by human language.
String input = "8:30 AM";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( "h:m a" , Locale.ENGLISH );
LocalTime localTime = LocalTime.parse ( input , formatter );
Dump to console.
System.out.println ( "localTime: " + localTime );
localTime: 08:30
Database
Next, the database. Eventually we should see JDBC drivers updated to directly handle the java.time types. Until then, we must convert from java.time types to the old java.sql types.
Convert From java.time to java.sql
For this Question, that means the java.sql.Time class. That old java.sql.Time class has a new method for convenient conversions, valueOf.
java.sql.Time sqlTime = java.sql.Time.valueOf ( localTime );
From there, the JDBC driver converts from the java.sql time to the database type. For this Question, that probably means the standard TIME SQL type.
Pass java.sql.* Object To Database Via JDBC Driver
Use a PreparedStatement to insert or update your data by passing that sqlTime variable seen above. Search StackOverflow.com for countless examples of such insert/update work in SQL.
I'm trying to convert some string that is in UTC time to a java Calendar object that should be set to GMT-5.
My current UTC string input is this:
UTC date : 20050329174411
I use this code (I detect the 'pattern' as shown below):
DateFormat dateFormat = new SimpleDateFormat(pattern);
Date date = dateFormat.parse(utcDate);
calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT-5"));
calendar.setTime(date);
I then printed the time like this:
calendar.getTime()
And I got this result:
GMT date : Tue Mar 29 17:44:11 EST 2005
I need to support theses date/time string patterns:
FORMAT_UTC4 = "yyyy";
FORMAT_UTC6 = "yyyyMM";
FORMAT_UTC8 = "yyyyMMdd";
FORMAT_UTC10 = "yyyyMMddHH";
FORMAT_UTC12 = "yyyyMMddHHmm";
FORMAT_UTC14 = "yyyyMMddHHmmss";
I would be expecting the time to be set to "12:44:11". I have read a couple of examples and I find date time handling pretty confusing. For me, it's always the same, I get some sort of string formatted UTC and I convert it to GMT-5. I really feel it should be easy!
Ref 1 : How can I get the current date and time in UTC or GMT in Java?
Ref 2 : How to handle calendar TimeZones using Java?
You must set the SimpleDateFormat's time zone to UTC before parsing the date. Else, it uses your default timezone.
And to display the date in the "GMT-5" timezone, you should use another DateFormat, with the timezone set to GMT-5, and format the date with this DateFormat. The toString() method of Date uses your default time zone to transform the date into something readable.
java.time
Note that GMT-5 or timezone offset of -05:00 hours is a fixed offset i.e. independent of the DST and type to represent a date-time with timezone offset is OffsetDateTime.
Demo:
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
public class Main {
public static void main(String[] args) {
Instant instant = Instant.ofEpochMilli(20050329174411L);
OffsetDateTime odt = instant.atOffset(ZoneOffset.of("-05:00"));
// Alternatively
// OffsetDateTime.ofInstant(instant, ZoneOffset.of("-05:00"));
System.out.println(odt);
}
}
Output:
2605-05-15T18:52:54.411-05:00
If you are looking for an automatic adjustment of timezone offset as per the DST, use ZonedDateTime.
Demo:
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class Main {
public static void main(String[] args) {
Instant instant = Instant.ofEpochMilli(20050329174411L);
ZonedDateTime zdt = instant.atZone(ZoneId.of("America/Chicago"));
// Alternatively
// ZonedDateTime.ofInstant(instant, ZoneId.of("America/Chicago"));
System.out.println(zdt);
}
}
Output:
2605-05-15T18:52:54.411-05:00[America/Chicago]
Learn more about java.time, the modern date-time API* from Trail: Date Time.
If at all you need an object of java.util.Calendar from this object of ZonedDateTime, you can do so as follows:
Calendar calendar = Calendar.getInstance();
calendar.setTime(Date.from(zdt.toInstant()));
* 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.
This is my Below function in which I am passing timestamp, I need only the date in return from the timestamp not the Hours and Second. With the below code I am getting-
private String toDate(long timestamp) {
Date date = new Date (timestamp * 1000);
return DateFormat.getInstance().format(date).toString();
}
This is the output I am getting.
11/4/01 11:27 PM
But I need only the date like this
2001-11-04
Any suggestions?
Use SimpleDateFormat instead:
private String toDate(long timestamp) {
Date date = new Date(timestamp * 1000);
return new SimpleDateFormat("yyyy-MM-dd").format(date);
}
Updated: Java 8 solution:
private String toDate(long timestamp) {
LocalDate date = Instant.ofEpochMilli(timestamp * 1000).atZone(ZoneId.systemDefault()).toLocalDate();
return date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
}
You can use this code to get the required results
protected Timestamp timestamp = new Timestamp(Calendar.getInstance().getTimeInMillis());
protected String today_Date=timestamp.toString().split(" ")[0];
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:
You can use Instant#ofEpochSecond to get an Instant out of the given timestamp and then use LocalDate.ofInstant to get a LocalDate out of the obtained Instant.
Demo:
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
public class Main {
public static void main(String[] args) {
// Test
System.out.println(toDate(1636120105L));
}
static LocalDate toDate(long timestamp) {
return LocalDate.ofInstant(Instant.ofEpochSecond(timestamp), ZoneId.systemDefault());
}
}
Output:
2021-11-05
ONLINE DEMO
Learn more about the modern Date-Time API from Trail: Date Time. Check this answer and this answer to learn how to use java.time API with JDBC.
* 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. Note that Android 8.0 Oreo already provides support for java.time.
Joda-Time
The Joda-Time library offers a LocalDate class to represent a date-only value without any time-of-day nor time zone.
Time Zone
Determining a date requires a time zone. A moment just after midnight in Paris means a date that is a day ahead of the same simultaneous moment in Montréal. If you neglect to specify a time zone, the JVM’s current default time zone is applied – probably not what you want as results may vary.
Example Code
long millisecondsSinceUnixEpoch = ( yourNumberOfSecondsSinceUnixEpoch * 1000 ); // Convert seconds to milliseconds.
DateTimeZone timeZone = DateTimeZone.forID( "America/Montreal" );
LocalDate localDate = new LocalDate( millisecondsSinceUnixEpoch, timeZone );
String output = localDate.toString(); // Defaults to ISO 8601 standard format, YYYY-MM-DD.
Previous Day
To get the day before, as requested in a comment.
LocalDate dayBefore = localDate.minusDays( 1 );
Convert to j.u.Date
The java.util.Date & .Calendar classes should be avoided as they are notoriously troublesome. But if required, you may convert.
java.util.Date date = localDate.toDate(); // Time-of-day set to earliest valid for that date.
I want to get the UTC time for 01/01/2100 in Java to '2100-01-01 00:00:00'. I am getting "2100-01-01 00:08:00". Any idea, how to correct this.
public Date getFinalTime() {
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Date finalTime = null;
try
{
finalTime = df.parse("01/01/2100");
} catch (ParseException e)
{
e.printStackTrace();
}
calendar.setTime(finalTime);
return calendar.getTime();
}
You need to specify the time zone for the SimpleDateFormat as well - currently that's parsing midnight local time which is ending up as 8am UTC.
TimeZone utc = TimeZone.getTimeZone("UTC");
Calendar calendar = Calendar.getInstance(utc);
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
df.setTimeZone(utc);
Date finalTime = null;
try
{
finalTime = df.parse("01/01/2100");
} catch (ParseException e)
{
e.printStackTrace();
}
calendar.setTime(finalTime);
As ever though, I would personally recommend using Joda Time which is far more capable in general. I'd be happy to translate your example into Joda Time if you want.
Additionally, I see you're returning calendar.getTime() - that's just the same as returning finalTime as soon as you've computed it.
Finally, just catching a ParseException and carrying on as if it didn't happen is a very bad idea. I'm hoping this is just sample code and it doesn't reflect your real method. Likewise I'm assuming that really you'll be parsing some other text - if you're not, then as Eyal said, you should just call methods on Calendar directly. (Or, again, use Joda Time.)
You need to set the time zone of the SimpleDateFormat object as well, otherwise it assumes the default time zone.
Anyway, it seems like using only a Calendar is enough in your case. Use its setters to set the right values for all fields (year, month, day, hour, etc), and then retrieve the 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 at 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 API:
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String strDate = "01/01/2100";
DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern("d/M/u", Locale.ENGLISH);
ZonedDateTime zdt = LocalDate.parse(strDate, dtfInput)
.atStartOfDay(ZoneId.of("Etc/UTC"));
// Default format
System.out.println(zdt);
// Getting and displaying LocalDateTime
LocalDateTime ldt = zdt.toLocalDateTime();
System.out.println(ldt);
// A custom format
DateTimeFormatter dtfOutput = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss", Locale.ENGLISH);
// Alternatively dtfOutput.format(ldt);
String formatted = dtfOutput.format(zdt);
System.out.println(formatted);
// Converting to some other types
OffsetDateTime odt = zdt.toOffsetDateTime();
Instant instant = zdt.toInstant();
System.out.println(odt);
System.out.println(instant);
}
}
Output:
2100-01-01T00:00Z[Etc/UTC]
2100-01-01T00:00
2100-01-01 00:00:00
2100-01-01T00:00Z
2100-01-01T00:00:00Z
ONLINE DEMO
The Z in the output is the timezone designator for zero-timezone offset. It stands for Zulu and specifies the Etc/UTC timezone (which has the timezone offset of +00:00 hours).
Note: The Date-Time without timezone name or timezone offset should be represented by LocalDateTime (which is used for events that are normally not represented with timezone information). In this sense, LocalDateTime is useless in this case and you should use ZonedDateTime itself or Instant or OffsetDateTime. I recommend you also check this answer and this answer if you are dealing with JDBC.
Learn more about java.time, 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.time
Like Arvind Kumar Avinash I very clearly recommend that you use java.time, the modern Java date and time API, for your date and time work. If what you want is a fixed (constant) date and time, use OffsetDateTime.of().
OffsetDateTime finalTime = OffsetDateTime.of(2100, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC);
System.out.println(finalTime);
Output:
2100-01-01T00:00Z
The trailing Z means UTC.
Tutorial link
Oracle tutorial: Date Time explaining how to use java.time.
TimeZone utc = TimeZone.getTimeZone("UTC");
Calendar calendar = Calendar.getInstance(utc);
DateFormat dateformat = new SimpleDateFormat("dd/MM/yyyy");
dateformat.setTimeZone(utc);
Timezone needs to be set.