I have a current date in Java like below:
String currentDate = CoreUtil.parseDate(new Date());
This returns the date for today in the form 2019-03-26.
I declared another date so that it should automatically add 7 days to the current date like below:
String defaultendDate=CoreUtil.parseDate(new Date()); + 7 days //example
So the defaultEnddate should be 2019-04-03
How would I accomplish this as I don't want to use any simple date formatter?
Also, I would like to store the date as it is in String for reasons and secondly, I only want date, not the time. I am not using Java 8 as well, so I can't really use LocalDate library here.
LocalDate is perfect for this job:
LocalDate.now().plusDays(7);
You can get your string representation with
.format(DateTimeFormatter.ISO_DATE);
If you're not able to use Java 8, then you have a few options:
Use the ThreeTen-Backport, which backports most functionality of the Java 8 JSR-310 API, normally available in the java.time package. See here for details. This package is available in Maven Central.
You can also use Joda Time. The peculiar thing is that these two projects have almost the same layout of their websites.
If you're otherwise not able to use ThreeTen-Backport or Joda Time, you can use this:
Calendar c = GregorianCalendar.getInstance();
c.add(Calendar.DATE, 7);
String s = new SimpleDateFormat("yyyy-MM-dd")
.format(c.getTime());
Warning
Many things are wrong with the old Date and Time API, see here. Use this only if you have no other option.
Use Calendar.
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH, 7);
Date defaultEndDate = cal.getTime();
Something like
LocalDate.now().plusWeeks(1);
would also do the cause.
Please, bare in mind using Java 8 Date/Time API for any operations with dates and times. as it addresses shortcomings of old Date and Calendar regarding thread safety, code design, time-zone logic and other.
UPDATE:
If you must use old Date/Time API, following code would suffice:
Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_MONTH, 7);
System.out.println("Adding seven days: " + calendar.getTime());
date = calendar.getTime();
//your code
String currentDate = CoreUtil.parseDate(new Date());
*
String dt = new SimpleDateFormat("yyyy.MM.dd").format(new Date()); // Start date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
c.add(Calendar.DATE, 7); // number of days to add
dt = sdf.format(c.getTime()); // dt is now the new date
System.out.println(dt);
*
Use java.util.Date try this one
Related
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.
My client/browser is in India and I get the timezoneoffset from javascript
using the following code:
var now = new Date();
var localOffSet = now.getTimezoneOffset(); -330 // for India
int localOffSetMin = (localOffSet)*(-1);
My server is located in New York so I get the offset for it using:
TimeZone timeZone = now.getTimeZone();
int serverOffset = timeZone.getRawOffset();
int serverOffSetMinutes = serverOffset / 60000; // -300 for America/New York
In order to find the local time on my machine, I use this:
int offSets = Math.abs(serverOffSetMinutes-localOffSetMin);
now.setTime(createDt); // createDt is date field value for some column
now.add(Calendar.MINUTE, offSets); // adds offset
Date localDt = now.getTime();
But the date/time I get is 1 hour ahead of the expected time. What am I missing?
Date and Time manipulation with Java SE
You can print a list of supported TimeZones by using the following code.
System.out.println(TimeZone.getAvailableIDs().toString());
You can then find and print the difference between the timezones with the following code. You must be mindful of daylight savings time.
public void printTimeZoneDifference(String from, String to) {
TimeZone easternStandardTime = TimeZone.getTimeZone(from);
TimeZone indiaStandardTime = TimeZone.getTimeZone(to);
long milliseconds = easternStandardTime.getRawOffset() - indiaStandardTime.getRawOffset() + easternStandardTime.getDSTSavings() - indiaStandardTime.getDSTSavings();
String difference = String.format("%02d min, %02d sec", TimeUnit.MILLISECONDS.toMinutes(milliseconds), TimeUnit.MILLISECONDS.toSeconds(milliseconds) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(milliseconds)));
System.out.println("The difference in time between" + easternStandardTime.getDisplayName() + " and " + indiaStandardTime.getDisplayName() + " is " + difference);
}
Although if I were to write something like this I would probably pass a TimeZone object as a parameter and keep the method solely responsible for substraction. Then I would either print the results or make it part of a different method. I didn't structure the post that way because I wanted to include all relevant code in the post.
Date and Time manipulation with Joda
This type of manipulation has already been solved in Java. The Joda Time Library is probably your best bet if you are doing a lot of date manipulation. If you are only manipulating time in this one instance then it would be a bit over kill to include the dependency in your runtime.
Again print out the TimeZones.
public void printDateTimeZones() {
for(String zone : DateTimeZone.getAvailableIDs()) {
System.out.println(zone);
}
}
Then you can return a String of the period (difference) between the two DateTimeZones using the default formatting with the following code.
public String printPeriod(String from, String to) {
Period period = new Period(new DateTime(DateTimeZone.forID(to)), new DateTime(DateTimeZone.forID(from)));
return PeriodFormat.getDefault().print(period);
}
Similarly Joda provides a format builder class which allows you to specify your preferred formatting.
public String printPeriod(String from, String to) {
PeriodFormatter formatter = new PeriodFormatterBuilder()
.printZeroRarelyFirst()
.appendYears().appendSuffix(" Years").appendSeparator(",")
.appendMonths().appendSuffix(" Months").appendSeparator(",")
.appendWeeks().appendSuffix(" Weeks").appendSeparator(",")
.appendDays().appendSuffix(" Days").appendSeparator(",")
.appendHours().appendSuffix(" Hours").appendSeparator(",")
.appendSeconds().appendSuffix(" Seconds").appendSeparator(",")
.appendMillis().appendSuffix(" Milliseconds")
.toFormatter();
return formatter.print(new Period(new DateTime(DateTimeZone.forID(from)), new DateTime(DateTimeZone.forID(to))));
}
A java.util.Date object has no timezone information. It has only a long value, which is the number of milliseconds from 1970-01-01T00:00:00Z (also known as "unix epoch" or just "epoch"). This value is absolutely independent of timezone (you can say "it's in UTC" as well).
To convert this value to another timezone, you don't need to do all these math between the timezones. You just get this millis value and convert it to the desired timezone.
To get the value from javascript, just do:
var d = new Date();
var millis = d.getTime();
The variable millis will contain the number of milliseconds from epoch. In the test I've made, this value is 1499101493296.
To create a java.util.Date object, just do:
Date date = new Date(1499101493296L);
To format this date in the timezone you want, use a SimpleDateFormat:
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));
System.out.println(sdf.format(date));
The output will be:
03/07/2017 22:34:53
If you want a different format, check the javadoc for more information.
Also note that I used a timezone name using IANA format (always in the format Continent/City, like America/Sao_Paulo or Europe/Berlin).
Avoid using the 3-letter abbreviations (like IST or EST) because they are ambiguous and not standard.
To use another timezone, you can use one the IANA's names - check all the available names using TimeZone.getAvailableIDs().
New Java 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.
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).
Although you can also use Joda-Time, it is in maintainance mode and is being replaced by the new APIs, so I don't recommend start a new project with it. Even in joda's website it says: "Note that Joda-Time is considered to be a largely “finished” project. No major enhancements are planned. If using Java SE 8, please migrate to java.time (JSR-310).".
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.
Once you have the millis value, the code for creating a date and converting to some timezone is very similar:
ZoneId zone = ZoneId.of("Asia/Kolkata");
ZonedDateTime z = Instant.ofEpochMilli(1499101493296L).atZone(zone);
System.out.println(z); // 2017-07-03T22:34:53.296+05:30[Asia/Kolkata]
The output will be:
2017-07-03T22:34:53.296+05:30[Asia/Kolkata]
If you want a different format, use a DateTimeFormatter:
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss x");
System.out.println(z.format(fmt)); // 03/07/2017 22:34:53 +0530
The output will be:
03/07/2017 22:34:53 +0530
If you want a different format, check the javadoc for more details.
To use another timezone, you can use one the IANA's names - check all the available names using ZoneId.getAvailableZoneIds().
How should I add 120 days to my current date which I got using simple date format?
I have seen few posts about it but couldn't get it to work,
My code is below:
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
//get current date time with Date()
Date date = new Date();
Do I need to use the Calendar library or can I just do it with simple date format?
Basically, you can simple use a Calendar which has the capacity to automatically roll the various fields of a date based on the changes to a single field, for example...
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE, 120);
date = cal.getTime();
Take a closer look at Calendar for more details.
Yes, there is a way to do this using Joda Time, but I could type this example quicker ;)
Update with JodaTime example
The following is an example using JodaTime. You could parse the String value directly using JodaTime, but since you've already done that, I've not bothered...
Date date = ...;
DateTime dt = new DateTime(date);
dt = dt.plusDays(120);
date = dt.toDate();
I would suggest you use Joda DateTime if possible. The advantage is it handles TimeZone very gracefully. Here's how to add days:
DateTime added = dt.plusDays(120);
Reference:
http://joda-time.sourceforge.net/apidocs/org/joda/time/DateTime.html#plusDays(int)
so i have a mssql database with a DateObjectCreated column of type DateTime. The values it will accept into the table are in the format 2013-12-23 12:23:56.567. However, my java program is creating a joda DateTime object with the format 2013-12-23T 12:23:56.567Z. this wont insert into my db. i need to either convert "2013-12-23T 12:23:56.567Z" to 2013-12-23 12:23:56.567 or find a way to allow my db table to accept "2013-12-23T 12:23:56.567Z" format
any help on this matter will be much appreciated
Many thanks
Billy
Controller
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
String formattedDate = formatter.format(date);//this gives me the string as i need it
DateTime dt = new DateTime(formattedDate);//here it adds the 'T' and 'Z'
ive tried
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
String formattedDate = formatter.format(date);//this gives me the string as i need it
Date dt = formatter.parse(formattedDate);//here it gives me the same as new Date()
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date myDate = formatter.parse(date);
2.enter link description here
The TO_DATE function can be used in Oracle/PLSQL. For example:
TO_DATE('2003/07/09', 'yyyy/mm/dd') would return a date value of July 9, 2003
TO_DATE('070903', 'MMDDYY') would return a date value of July 9, 2003
TO_DATE('20020315', 'yyyymmdd') would return a date value of Mar 15, 2002
Your DB column has a DateTime type. The text representation of your date is irrelevant for persisting it.
Regardless of the API you are using (JDBC, JPA, Hibernate) there will be something like a "setDateTime(Date date)" method that allows you to pass in a java.util.Date or java.sql.Date or a Java long. You can use the milli-second value of your Joda DateTime object to create whatever is required by the API.
You are working way too hard.
Convert your Joda-Time DateTime object to a java.util.Date. Just call toDate() method.
Pass Date instance to your framework or SQL.
The answer by Ralf is correct in its first part, but is wrong in the end in that you need not deal with milliseconds. Joda-Time knows how to convert to java.util.Date.
org.joda.time.DateTime now = new org.joda.time.DateTime();
java.util.Date nowAsJavaUtilDate = now.toDate();
By the way, the java.sql.Date class is simply a very thin subclass of java.util.Date. So don't let that throw you.
In the future, this will become even easier. Java 8 brings the new JSR 310 classes in the java.time.* package. These classes supplant the mess that is java.util.Date/Calendar. They are inspired by Joda-Time but are entirely re-architected. As they are a built-in part of Java, expect JDBC and related frameworks to be updated to handle these new types directly.
I hope this is not a repeat.
I checked other searches here and all of them seem to talk about "displaying" the date in the right TimeZone format using SimpleDateFormat.
However, my problem is I obtain an XMLGregorianCalendar Object which is let us say in "CET".
I have to find out the format from this object and send the current time also in the same TimeZone as the server.
For eg: I need an XMLGregorianCalendar Object that returns me in this format(with Timezone):
2012-09-19T15:23:36.421+02:00
So I just tried this following snippet which seems to only return the time in local Timezone :(
TimeZone utc = TimeZone.getTimeZone("CET");
GregorianCalendar gc = new GregorianCalendar();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ");
df.setTimeZone(utc);
System.out.println(" - Gregorian UTC [" + df.format(gc.getTime()) + "]")
XMLGregorianCalendar currServTime = DatatypeFactory.newInstance().newXMLGregorianCalendar(gc);
System.out.println("currServTime is "+currServTime);
You should include the time zone you're interested in in the GregorianCalendar, either by passing it to the constructor or by setting it afterwards. So either of these lines should work for you:
GregorianCalendar gc = new GregorianCalendar(utc);
gc.setTimeZone(utc);