I want to find out the day of the date in Java for a date like 27-04-2011.
I tried to use this, but it doesn't work:
Calendar cal = Calendar.getInstance();
int val = cal.get(Calendar.DAY_OF_WEEK);
It gives the integer value, not the String output I want. I am not getting the correct value I want. For example it is giving me value 4 for the date 28-02-2011 where it should be 2 because Sunday is the first week day.
Yes, you've asked it for the day of the week - and February 28th was a Monday, day 2. Note that in the code you've given, you're not actually setting the date anywhere - it's just using the current date, which is a Wednesday, which is why you're getting 4. If you could show how you're trying to set the calendar to a different date (e.g. 28th of February) we can work out why that's not working for you.
If you want it formatted as text, you can use SimpleDateFormat and the "E" specifier. For example (untested):
SimpleDateFormat formatter = new SimpleDateFormat("EEE");
String text = formatter.format(cal.getTime());
Personally I would avoid using Calendar altogether though - use Joda Time, which is a far superior date and time API.
Calendar cal=Calendar.getInstance();
System.out.println(new SimpleDateFormat("EEE").format(cal.getTime()));
Output
Wed
See Also
SimpleDateFormat
String dayNames[] = new DateFormatSymbols().getWeekdays();
Calendar date1 = Calendar.getInstance();
System.out.println("Today is a "
+ dayNames[date1.get(Calendar.DAY_OF_WEEK)]);
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 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 Date-Time API:
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.TextStyle;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String input = "27-04-2011";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("d-M-u", Locale.ENGLISH);
LocalDate date = LocalDate.parse(input, dtf);
DayOfWeek dow = date.getDayOfWeek();
System.out.println(dow);
// String value
String strDay = dow.getDisplayName(TextStyle.FULL, Locale.ENGLISH);
System.out.println(strDay);
strDay = dow.getDisplayName(TextStyle.SHORT, Locale.ENGLISH);
System.out.println(strDay);
// Alternatively
strDay = date.format(DateTimeFormatter.ofPattern("EEEE", Locale.ENGLISH));
System.out.println(strDay);
strDay = date.format(DateTimeFormatter.ofPattern("EEE", Locale.ENGLISH));
System.out.println(strDay);
}
}
Output:
WEDNESDAY
Wednesday
Wed
Wednesday
Wed
ONLINE DEMO
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.
See the JavaDoc of the DAY_OF_WEEK field. It points to 7 constants SUNDAY..SATURDAY that show how to decode the int return value of cal.get(Calendary.DAY_OF_WEEK). Are you sure that
Calendar cal = Calendar.getInstance();
cal.set(2011, 02, 28);
cal.get(Calendar.DAY_OF_WEEK);
returns the wrong value for you?
Try following:
Calendar cal=Calendar.getInstance();
int val = cal.get(Calendar.DAY_OF_WEEK);
System.out.println(new DateFormatSymbols().getWeekdays()[val]);
or
Calendar cal=Calendar.getInstance();
String dayName = new DateFormatSymbols().getWeekdays()[cal
.get(Calendar.DAY_OF_WEEK)];
System.out.println(dayName);
Calendar cal=Calendar.getInstance();
cal.set(2011, 2, 28);
int val = cal.get(Calendar.DAY_OF_WEEK);
System.out.println(val);
Look at SimpleDateFormat and propably Locale.
If you need the exact date value in the month you need to use Calendar:DAY_OF_MONTH it will return the exact date in the month starting from 1.
//Current date is 07-06-2021 and this will return 7
Calendar cal = Calendar.getInstance();
int val = cal.get(Calendar.DAY_OF_MONTH);
System.out.println("Date in month:"+val);
//If you want the day of the week in text better use the
//SimpleDateFormat, since Calendar API will return the integer value in
// the week if we given Calendar.DAY_OF_WEEK
String dayWeekText = new SimpleDateFormat("EEEE").format(cal.getTime());
System.out.println("Day of week:"+dayWeekText);
As suggested in the comment Java Date API have all these feature available. Java 8 introduced new APIs for Date and Time to address the shortcomings of the older java.util.Date and java.util.Calendar.
The same can be achieved using Date API in Java
LocalDate localDate = LocalDate.parse("2021-06-08"); //2021 June 08 Tuesday
System.out.println(localDate.dayOfWeek().getAsText()); //Output as : Tuesday
System.out.println(localDate.dayOfWeek().getAsShortText()); //Output as : Tue
System.out.println(localDate.dayOfMonth().get()); //Output as current date
Related
I'm working with a date in this format: yyyy-mm-dd.
How can I increment this date by one day?
Something like this should do the trick:
String dt = "2008-01-01"; // Start date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
c.setTime(sdf.parse(dt));
c.add(Calendar.DATE, 1); // number of days to add
dt = sdf.format(c.getTime()); // dt is now the new date
UPDATE (May 2021): This is a really outdated answer for old, old Java. For Java 8 and above, see https://stackoverflow.com/a/20906602/314283
Java does appear to be well behind the eight-ball compared to C#. This utility method shows the way to do in Java SE 6 using the Calendar.add method (presumably the only easy way).
public class DateUtil
{
public static Date addDays(Date date, int days)
{
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE, days); //minus number would decrement the days
return cal.getTime();
}
}
To add one day, per the question asked, call it as follows:
String sourceDate = "2012-02-29";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date myDate = format.parse(sourceDate);
myDate = DateUtil.addDays(myDate, 1);
java.time
On Java 8 and later, the java.time package makes this pretty much automatic. (Tutorial)
Assuming String input and output:
import java.time.LocalDate;
public class DateIncrementer {
static public String addOneDay(String date) {
return LocalDate.parse(date).plusDays(1).toString();
}
}
I prefer to use DateUtils from Apache. Check this http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/time/DateUtils.html. It is handy especially when you have to use it multiple places in your project and would not want to write your one liner method for this.
The API says:
addDays(Date date, int amount) : Adds a number of days to a date returning a new object.
Note that it returns a new Date object and does not make changes to the previous one itself.
SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd" );
Calendar cal = Calendar.getInstance();
cal.setTime( dateFormat.parse( inputString ) );
cal.add( Calendar.DATE, 1 );
Construct a Calendar object and call add(Calendar.DATE, 1);
Java 8 added a new API for working with dates and times.
With Java 8 you can use the following lines of code:
// parse date from yyyy-mm-dd pattern
LocalDate januaryFirst = LocalDate.parse("2014-01-01");
// add one day
LocalDate januarySecond = januaryFirst.plusDays(1);
Take a look at Joda-Time (https://www.joda.org/joda-time/).
DateTimeFormatter parser = ISODateTimeFormat.date();
DateTime date = parser.parseDateTime(dateString);
String nextDay = parser.print(date.plusDays(1));
Please note that this line adds 24 hours:
d1.getTime() + 1 * 24 * 60 * 60 * 1000
but this line adds one day
cal.add( Calendar.DATE, 1 );
On days with a daylight savings time change (25 or 23 hours) you will get different results!
you can use Simple java.util lib
Calendar cal = Calendar.getInstance();
cal.setTime(yourDate);
cal.add(Calendar.DATE, 1);
yourDate = cal.getTime();
Date today = new Date();
SimpleDateFormat formattedDate = new SimpleDateFormat("yyyyMMdd");
Calendar c = Calendar.getInstance();
c.add(Calendar.DATE, 1); // number of days to add
String tomorrow = (String)(formattedDate.format(c.getTime()));
System.out.println("Tomorrows date is " + tomorrow);
This will give tomorrow's date. c.add(...) parameters could be changed from 1 to another number for appropriate increment.
If you are using Java 8, then do it like this.
LocalDate sourceDate = LocalDate.of(2017, Month.MAY, 27); // Source Date
LocalDate destDate = sourceDate.plusDays(1); // Adding a day to source date.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); // Setting date format
String destDate = destDate.format(formatter)); // End date
If you want to use SimpleDateFormat, then do it like this.
String sourceDate = "2017-05-27"; // Start date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
calendar.setTime(sdf.parse(sourceDate)); // parsed date and setting to calendar
calendar.add(Calendar.DATE, 1); // number of days to add
String destDate = sdf.format(calendar.getTime()); // End date
Since Java 1.5 TimeUnit.DAYS.toMillis(1) looks more clean to me.
SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd" );
Date day = dateFormat.parse(string);
// add the day
Date dayAfter = new Date(day.getTime() + TimeUnit.DAYS.toMillis(1));
long timeadj = 24*60*60*1000;
Date newDate = new Date (oldDate.getTime ()+timeadj);
This takes the number of milliseconds since epoch from oldDate and adds 1 day worth of milliseconds then uses the Date() public constructor to create a date using the new value. This method allows you to add 1 day, or any number of hours/minutes, not only whole days.
In Java 8 simple way to do is:
Date.from(Instant.now().plusSeconds(SECONDS_PER_DAY))
It's very simple, trying to explain in a simple word.
get the today's date as below
Calendar calendar = Calendar.getInstance();
System.out.println(calendar.getTime());// print today's date
calendar.add(Calendar.DATE, 1);
Now set one day ahead with this date by calendar.add method which takes (constant, value). Here constant could be DATE, hours, min, sec etc. and value is the value of constant. Like for one day, ahead constant is Calendar.DATE and its value are 1 because we want one day ahead value.
System.out.println(calendar.getTime());// print modified date which is tomorrow's date
Thanks
startCalendar.add(Calendar.DATE, 1); //Add 1 Day to the current Calender
In java 8 you can use java.time.LocalDate
LocalDate parsedDate = LocalDate.parse("2015-10-30"); //Parse date from String
LocalDate addedDate = parsedDate.plusDays(1); //Add one to the day field
You can convert in into java.util.Date object as follows.
Date date = Date.from(addedDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
You can formate LocalDate into a String as follows.
String str = addedDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
With Java SE 8 or higher you should use the new Date/Time API
int days = 7;
LocalDate dateRedeemed = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/YYYY");
String newDate = dateRedeemed.plusDays(days).format(formatter);
System.out.println(newDate);
If you need to convert from java.util.Date to java.time.LocalDate, you may use this method.
public LocalDate asLocalDate(Date date) {
Instant instant = date.toInstant();
ZonedDateTime zdt = instant.atZone(ZoneId.systemDefault());
return zdt.toLocalDate();
}
With a version prior to Java SE 8 you may use Joda-Time
Joda-Time provides a quality replacement for the Java date and time
classes and is the de facto standard date and time library for Java
prior to Java SE 8
int days = 7;
DateTime dateRedeemed = DateTime.now();
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/uuuu");
String newDate = dateRedeemed.plusDays(days).toString(formatter);
System.out.println(newDate);
Apache Commons already has this DateUtils.addDays(Date date, int amount) http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/time/DateUtils.html#addDays%28java.util.Date,%20int%29 which you use or you could go with the JodaTime to make it more cleaner.
Just pass date in String and number of next days
private String getNextDate(String givenDate,int noOfDays) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
String nextDaysDate = null;
try {
cal.setTime(dateFormat.parse(givenDate));
cal.add(Calendar.DATE, noOfDays);
nextDaysDate = dateFormat.format(cal.getTime());
} catch (ParseException ex) {
Logger.getLogger(GR_TravelRepublic.class.getName()).log(Level.SEVERE, null, ex);
}finally{
dateFormat = null;
cal = null;
}
return nextDaysDate;
}
If you want to add a single unit of time and you expect that other fields to be incremented as well, you can safely use add method. See example below:
SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
cal.set(1970,Calendar.DECEMBER,31);
System.out.println(simpleDateFormat1.format(cal.getTime()));
cal.add(Calendar.DATE, 1);
System.out.println(simpleDateFormat1.format(cal.getTime()));
cal.add(Calendar.DATE, -1);
System.out.println(simpleDateFormat1.format(cal.getTime()));
Will Print:
1970-12-31
1971-01-01
1970-12-31
Use the DateFormat API to convert the String into a Date object, then use the Calendar API to add one day. Let me know if you want specific code examples, and I can update my answer.
Try this method:
public static Date addDay(int day) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.add(Calendar.DATE, day);
return calendar.getTime();
}
It's simple actually.
One day contains 86400000 milliSeconds.
So first you get the current time in millis from The System by usingSystem.currentTimeMillis() then
add the 84000000 milliSeconds and use the Date Class to generate A date format for the milliseconds.
Example
String Today = new Date(System.currentTimeMillis()).toString();
String Today will be 2019-05-9
String Tommorow = new Date(System.currentTimeMillis() + 86400000).toString();
String Tommorow will be 2019-05-10
String DayAfterTommorow = new Date(System.currentTimeMillis() + (2 * 86400000)).toString();
String DayAfterTommorow will be 2019-05-11
You can use this package from "org.apache.commons.lang3.time":
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date myNewDate = DateUtils.addDays(myDate, 4);
Date yesterday = DateUtils.addDays(myDate, -1);
String formatedDate = sdf.format(myNewDate);
If you are using Java 8, java.time.LocalDate and java.time.format.DateTimeFormatter can make this work quite simple.
public String nextDate(String date){
LocalDate parsedDate = LocalDate.parse(date);
LocalDate addedDate = parsedDate.plusDays(1);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-mm-dd");
return addedDate.format(formatter);
}
The highest voted answer uses legacy java.util date-time API which was the correct thing to do in 2009 when the question was asked. In March 2014, java.time API supplanted the error-prone legacy date-time API. Since then, it is strongly recommended to use this modern date-time API.
I'm working with a date in this format: yyyy-mm-dd
You have used the wrong letter for the month, irrespective of whether you are using the legacy parsing/formatting API or the modern one. The letter m is used for minute-of-hour and the correct letter for month-of-year is M.
yyyy-MM-dd is the default format of java.time.LocalDate
The java.time API is based on ISO 8601 standards and therefore it does not require specifying a DateTimeFormatter explicitly to parse a date-time string if it is already in ISO 8601 format. Similarly, the toString implementation of a java.time type returns a string in ISO 8601 format. Check LocalDate#parse and LocalDate#toString for more information.
Ways to increment a local date by one day
There are three options:
LocalDate#plusDays(long daysToAdd)
LocalDate#plus(long amountToAdd, TemporalUnit unit): It has got some additional capabilities e.g. you can use it to increment a local date by days, weeks, months, years etc.
LocalDate#plus(TemporalAmount amountToAdd): You can specify a Period (or any other type implementing the TemporalAmount) to add.
Demo:
import java.time.Instant;
import java.time.LocalDate;
import java.time.Period;
import java.time.temporal.ChronoUnit;
public class Main {
public static void main(String[] args) {
// Parsing
LocalDate ldt = LocalDate.parse("2020-10-20");
System.out.println(ldt);
// Incrementing by one day
LocalDate oneDayLater = ldt.plusDays(1);
System.out.println(oneDayLater);
// Alternatively
oneDayLater = ldt.plus(1, ChronoUnit.DAYS);
System.out.println(oneDayLater);
oneDayLater = ldt.plus(Period.ofDays(1));
System.out.println(oneDayLater);
String desiredString = oneDayLater.toString();
System.out.println(desiredString);
}
}
Output:
2020-10-20
2020-10-21
2020-10-21
2020-10-21
2020-10-21
How to switch from the legacy to the modern date-time API?
You can switch from the legacy to the modern date-time API using Date#toInstant on a java-util-date instance. Once you have an Instant, you can easily obtain other date-time types of java.time API. An Instant represents a moment in time and is independent of a time-zone i.e. it represents a date-time in UTC (often displayed as Z which stands for Zulu-time and has a ZoneOffset of +00:00).
Demo:
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.Date;
public class Main {
public static void main(String[] args) {
Date date = new Date();
Instant instant = date.toInstant();
System.out.println(instant);
ZonedDateTime zdt = instant.atZone(ZoneId.of("Asia/Kolkata"));
System.out.println(zdt);
OffsetDateTime odt = instant.atOffset(ZoneOffset.of("+05:30"));
System.out.println(odt);
// Alternatively, using time-zone
odt = instant.atZone(ZoneId.of("Asia/Kolkata")).toOffsetDateTime();
System.out.println(odt);
LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneId.of("Asia/Kolkata"));
System.out.println(ldt);
// Alternatively,
ldt = instant.atZone(ZoneId.of("Asia/Kolkata")).toLocalDateTime();
System.out.println(ldt);
}
}
Output:
2022-11-12T12:52:18.016Z
2022-11-12T18:22:18.016+05:30[Asia/Kolkata]
2022-11-12T18:22:18.016+05:30
2022-11-12T18:22:18.016+05:30
2022-11-12T18:22:18.016
2022-11-12T18:22:18.016
Learn more about the modern Date-Time API from Trail: Date Time.
Let's clarify the use case: You want to do calendar arithmetic and start/end with a java.util.Date.
Some approaches:
Convert to string and back with SimpleDateFormat: This is an inefficient solution.
Convert to LocalDate: You would lose any time-of-day information.
Convert to LocalDateTime: This involves more steps and you need to worry about timezone.
Convert to epoch with Date.getTime(): This is efficient but you are calculating with milliseconds.
Consider using java.time.Instant:
Date _now = new Date();
Instant _instant = _now.toInstant().minus(5, ChronoUnit.DAYS);
Date _newDate = Date.from(_instant);
You can do this just in one line.
e.g to add 5 days
Date newDate = Date.from(Date().toInstant().plus(5, ChronoUnit.DAYS));
to subtract 5 days
Date newDate = Date.from(Date().toInstant().minus(5, ChronoUnit.DAYS));
I am trying to convert the string to date and i want that date to be in this format 'yyyy-MM-d HH:mm:ss' and i no how to get this format in string my question is i want to get Date in above format not as string but as 'Date '?
i am doing in this way
for(int k=0;k<12;k++)//for the months
{
//i have added if condtion for the months with 31 and 30 and 28 days
Calendar dateFromCal = Calendar.getInstance();
dateFromCal.setTime(date);
dateFromCal.set(year, k, 1, 0, 0, 0);
Calendar dateToCal = Calendar.getInstance();
dateToCal.setTime(date);
dateToCal.set(year, k, 31, 23, 59, 59);
//i have set the date format as 'yyyy:MM:dd HH:mm:ss'
dateFrom = dateFormat.format(dateFromCal.getTime());
dateTo = dateFormat.format(dateToCal.getTime());
fromdate = (Date)dateFormat.parse(dateFrom);
todate = (Date)dateFormat.parse(dateTo);
}
by using above code i am getting the date in the following format
Sat Nov 01 00:00:00 GMT 2014
but i want the date format to be as
2014-11-01 00:00:00
NOTE:I want this result as Date not as String
Please give me solution for this
Thanks....
i want to get Date in above format not as string but as 'Date '?
You're asking for a Date in a particular format - that's like saying "I want an int in hex format." A Date doesn't have a format - it's just an instant in time. It doesn't know about a calendar system or a time zone - it's just a number of milliseconds since the Unix epoch. If you want a formatted value, that's a string.
You should probably just keep the Date as it is, and format it later on, closer to the UI.
NOTE:I want this result as Date not as String
Short answer: It is NOT possible.
Details:
A java.util.Date object simply represents an instant on the timeline — a wrapper around the number of milliseconds since the UNIX epoch (January 1, 1970, 00:00:00 GMT). Since it does not hold any timezone information, its toString function applies the JVM's timezone to return a String in the format, EEE MMM dd HH:mm:ss zzz yyyy, derived from this milliseconds value. To get the String representation of the java.util.Date object in a different format and timezone, you need to use SimpleDateFormat with the desired format and the applicable timezone e.g.
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX", Locale.ENGLISH);
sdf.setTimeZone(TimeZone.getTimeZone("America/New_York"));
String strDateNewYork = sdf.format(date);
sdf.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
String strDateUtc = sdf.format(date);
In fact, none of the standard Date-Time classes has an attribute to hold the formatting information. Even if some library or custom class promises to do so, it is breaking the Single Responsibility Principle. A Date-Time object is supposed to store the information about Date, Time, Timezone etc., not about the formatting. The only way to represent a Date-Time object in the desired format is by formatting it into a String using a Date-Time parsing/formatting type:
For the modern Date-Time API: java.time.format.DateTimeFormatter
For the legacy Date-Time API: java.text.SimpleDateFormat
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.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
int year = 2021;
int month = 6;
int hour = 23;
int minute = 59;
int second = 59;
LocalDateTime ldt = LocalDate.of(year, month, 1)
.with(TemporalAdjusters.lastDayOfMonth())
.atTime(LocalTime.of(hour, minute, second));
// Default format i.e. ldt#toString
System.out.println(ldt);
// Custom format
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss", Locale.ENGLISH);
String formatted = dtf.format(ldt);
System.out.println(formatted);
}
}
Output:
2021-06-30T23:59:59
2021-06-30 23:59:59
ONLINE DEMO
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.
I had same problem with one API that was expecting particular format (javax.xml.datatype.XMLGregorianCalendar). In my case I solve this by the help of java 7
and
my_date.setTimezone(DatatypeConstants.FIELD_UNDEFINED);
By doing so you can get your final result for date with 00:00:00.
This is a simple method that takes care of formatting from String to Date:
` see code below:
public XMLGregorianCalendar formatToGregorianDate(String myDate) {
//actual Date format should be "dd-MMM-yy", but SimpleDateFormat accepts only this one
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
//Date is accepted only without time or zone
date = simpleDateFormat.parse(myDate.substring(0, 10));
} catch (ParseException e) {
System.out.println("Date can't be parsed to required format!");
e.printStackTrace();
}
GregorianCalendar gregorianCalendar = (GregorianCalendar) GregorianCalendar.getInstance();
gregorianCalendar.setTime(date);
XMLGregorianCalendar result = null;
try {
result = DatatypeFactory.newInstance().newXMLGregorianCalendar(gregorianCalendar);
//date must be sent without time
result.setTimezone(DatatypeConstants.FIELD_UNDEFINED);
} catch (DatatypeConfigurationException e) {
System.out.println("XMLGregorianCalendar can't parse the Date format!");
e.printStackTrace();
}
return result;
}`
Maybe you'll just need to adapt it for your needs, I don't know what do you need.
FYI - Note that I'm using java.util.Date. Maybe there is better logic, but this one works for sure.
Hope it helps.
How to reduce one month from current date and want to sore in java.util.Date variable
im using this code but it's shows error in 2nd line
java.util.Date da = new Date();
da.add(Calendar.MONTH, -1); //error
How to store this date in java.util.Date variable?
Use Calendar:
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, -1);
Date result = cal.getTime();
Starting from Java 8, the suggested way is to use the Date-Time API rather than Calendar.
If you want a Date object to be returned:
Date date = Date.from(ZonedDateTime.now().minusMonths(1).toInstant());
If you don't need exactly a Date object, you can use the classes directly, provided by the package, even to get dates in other time-zones:
ZonedDateTime dateInUTC = ZonedDateTime.now(ZoneId.of("Pacific/Auckland")).minusMonths(1);
Calendar calNow = Calendar.getInstance()
// adding -1 month
calNow.add(Calendar.MONTH, -1);
// fetching updated time
Date dateBeforeAMonth = calNow.getTime();
you can use Calendar
java.util.Date da = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(da);
cal.add(Calendar.MONTH, -1);
da = cal.getTime();
Using new java.time package in Java8 and Java9
import java.time.LocalDate;
LocalDate mydate = LocalDate.now(); // Or whatever you want
mydate = mydate.minusMonths(1);
The advantage to using this method is that you avoid all the issues about varying month lengths and have more flexibility in adjusting dates and ranges. The Local part also is Timezone smart so it's easy to convert between them.
As an aside, using java.time you can also get the day of the week, day of the month, all days up to the last of the month, all days up to a certain day of the week, etc.
mydate.plusMonths(1);
mydate.with(TemporalAdjusters.next(DayOfWeek.SUNDAY)).getDayOfMonth();
mydate.with(TemporalAdjusters.lastDayOfMonth());
Using JodaTime :
Date date = new DateTime().minusMonths(1).toDate();
JodaTime provides a convenient API for date manipulation.
Note that similar Date API will be introduced in JDK8 with the JSR310.
You can also use the DateUtils from apache common. The library also supports adding Hour, Minute, etc.
Date date = DateUtils.addMonths(new Date(), -1)
raduce 1 month of JDF
Date dateTo = new SimpleDateFormat("yyyy/MM/dd").parse(jdfMeTo.getJulianDate());
Calendar cal = Calendar.getInstance();
cal.setTime(dateTo);
cal.add(Calendar.MONTH, -1);
Date dateOf = cal.getTime();
Log.i("dateOf", dateOf.getTime() + "");
jdfMeOf.setJulianDate(cal.get(Calendar.DAY_OF_YEAR), cal.get(Calendar.DAY_OF_MONTH),
cal.get(Calendar.DAY_OF_WEEK_IN_MONTH));
I have a date string of 1/1/1970 8:00 AM
The correct millis should be 8 hours * 60 minutes per hour * 60000 milliseconds per minute = 28800000
However, using Date.parse(dateString) returns 50400000
What am I not understanding?
Edit
I originally tried using date.getTime();
Here's my original code:
SimpleDateFormat dateFmt = new SimpleDateFormat("MM/dd/yyyy h:mm a");
dateFmt.setTimeZone(TimeZone.getTimeZone("UTC"));
StringBuilder sb = new StringBuilder();
sb.append(month).append("/");
sb.append(day).append("/");
sb.append(year).append(" ");
sb.append(pad(hour)).append(":");
sb.append(pad(minute)).append(" ");;
sb.append(ampm);
Date date = new Date();
date = dateFmt.parse(sb.toString());
date.getTime()
This is almost certainly the problem:
If no time zone is specified, the local time zone is assumed.
My guess is that you're in a time zone which was at UTC-6 at the Unix epoch, so 8am local time was 2pm UTC.
Then there's the more fundamental problem of you using deprecated methods when there are better alternative (SimpleDateFormat, which allows you to set the time zone) available. Methods are deprecated for a reason. You shouldn't just use deprecated methods regardless, otherwise you'll keep running into things like this.
In fact, you'd be better off using Joda Time if you possibly can - but at least stay away from the deprecated methods in Date.
Sample code:
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy h:mm aa", Locale.US);
format.setTimeZone(TimeZone.getTimeZone("UTC"));
long millis = format.parse(text).getTime();
You may want to change dd/MM to MM/dd, depending on what format your dates are going to be in - we can't tell from "01/01". Note the explicit setting of both time zone and locale.
Its because of your local timezone. Use Simple date format with timezone as below to get your desired value against UTC timezone:
DateFormat format = new SimpleDateFormat("MM/dd/yyyy hh:mm a");
String dateS = "1/1/1970 8:00 AM";
format.setTimeZone(TimeZone.getTimeZone("UTC"));
format.setLenient(true);
Date date = format.parse(dateS);
System.out.println(date.getTime()); //<-- prints 28800000
or more compact:
DateFormat format = new SimpleDateFormat("MM/dd/yyyy hh:mm a");
format.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = format.parse("1/1/1970 8:00 AM");
System.out.println(date.getTime()); //<-- prints 28800000
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 do not need to form the string: You can use LocalDateTime#of to create an instance of LocalDateTime which can be converted into an Instant in order to get the number of milliseconds from the Unix epoch.
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
public class Main {
public static void main(String[] args) {
int year = 1970, month = 1, dayOfMonth = 1, hour = 8, minute = 0;
LocalDateTime ldt = LocalDateTime.of(year, month, dayOfMonth, hour, minute);
Instant instant = ldt.toInstant(ZoneOffset.UTC);
System.out.println(instant.toEpochMilli());
}
}
Output:
28800000
ONLINE DEMO
If you already have a date-time string in the given format:
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/d/u h:m a", Locale.ENGLISH);
String strDateTime = "1/1/1970 8:00 AM";
LocalDateTime ldt = LocalDateTime.parse(strDateTime, dtf);
Instant instant = ldt.toInstant(ZoneOffset.UTC);
System.out.println(instant.toEpochMilli());
}
}
Output:
28800000
ONLINE DEMO
An Instant represents an instantaneous point on the timeline in UTC.
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.
I know the week number of the year, a week is start from Sunday, then Monday, Tuesday...,Saturday.
Since I know the week number, what's the efficient way to get the dates of the specific week by using Java code??
If you don't want external library, just use calendar.
SimpleDateFormat sdf = new SimpleDateFormat("MM dd yyyy");
Calendar cal = Calendar.getInstance();
cal.set(Calendar.WEEK_OF_YEAR, 23);
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.println(sdf.format(cal.getTime()));
Pure Java 8 / java.time solution
Based on this:
final long calendarWeek = 34;
LocalDate desiredDate = LocalDate.now()
.with(IsoFields.WEEK_OF_WEEK_BASED_YEAR, calendarWeek)
.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
You can use the joda time library
int weekNumber = 10;
DateTime weekStartDate = new DateTime().withWeekOfWeekyear(weekNumber);
DateTime weekEndDate = new DateTime().withWeekOfWeekyear(weekNumber + 1);
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:
The first step is to find the first day of the week and as the second step, we just need to iterate all the seven days starting with this date.
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.
Demo of the first step:
import java.time.LocalDate;
import java.time.Year;
import java.time.temporal.WeekFields;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
// Test
int weekNumber = 34;
System.out.println(getFirstDayOfWeek(weekNumber, Locale.UK));
System.out.println(getFirstDayOfWeek(weekNumber, Locale.US));
}
static LocalDate getFirstDayOfWeek(int weekNumber, Locale locale) {
return LocalDate
.of(Year.now().getValue(), 2, 1)
.with(WeekFields.of(locale).getFirstDayOfWeek())
.with(WeekFields.of(locale).weekOfWeekBasedYear(), weekNumber);
}
}
Output:
2021-08-23
2021-08-15
ONLINE DEMO
Demo of the second step:
import java.time.LocalDate;
import java.time.Year;
import java.time.temporal.WeekFields;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Main {
public static void main(String[] args) {
// Test
getAllDaysOfTheWeek(34, Locale.US).forEach(System.out::println);
}
static LocalDate getFirstDayOfWeek(int weekNumber, Locale locale) {
return LocalDate
.of(Year.now().getValue(), 2, 1)
.with(WeekFields.of(locale).getFirstDayOfWeek())
.with(WeekFields.of(locale).weekOfWeekBasedYear(), weekNumber);
}
static List<LocalDate> getAllDaysOfTheWeek(int weekNumber, Locale locale) {
LocalDate firstDayOfWeek = getFirstDayOfWeek(weekNumber, locale);
return IntStream
.rangeClosed(0, 6)
.mapToObj(i -> firstDayOfWeek.plusDays(i))
.collect(Collectors.toList());
}
}
Output:
2021-08-15
2021-08-16
2021-08-17
2021-08-18
2021-08-19
2021-08-20
2021-08-21
ONLINE DEMO
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.
You did not mention what return type do you exactly need but this code should prove useful to you. sysouts and formatter are just to show you the result.
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
cal.set(Calendar.WEEK_OF_YEAR, 30);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
System.out.println(formatter.format(cal.getTime()));
cal.add(Calendar.DAY_OF_WEEK, 6);
System.out.println(formatter.format(cal.getTime()));
This answer is pretty much same as others. But, here it goes:
int year = 2018;
int week = 27;
int day = 1; //assuming week starts from sunday
Calendar calendar = Calendar.getInstance();
calendar.setWeekDate(year, week, day);
System.out.println(calendar.getTime());
for(int i=1; i<=7; i++) {
if(i <= 3) {
LocalDate desiredDate = LocalDate.now()
.with(IsoFields.WEEK_OF_WEEK_BASED_YEAR, 26)
.with(TemporalAdjusters.previousOrSame(DayOfWeek.of(i)));
System.out.println(desiredDate.format(DateTimeFormatter.ofPattern("dd/MM/yyyy")));
} else {
LocalDate desiredDate = LocalDate.now()
.with(IsoFields.WEEK_OF_WEEK_BASED_YEAR, 26)
.with(TemporalAdjusters.nextOrSame(DayOfWeek.of(i)));
System.out.println(desiredDate.format(DateTimeFormatter.ofPattern("dd/MM/yyyy")));
}
}
This snippet provides dates starting from monday to sunday based on the given week number
output:
28/06/2021
29/06/2021
30/06/2021
01/07/2021
02/07/2021
03/07/2021
04/07/2021
To verify check https://www.epochconverter.com/weeks/2021