Java: Date changes after parsing and applying new pattern - java

I'm trying to convert a user-legible time String to an SQL-compatible String. Therefore I use the following code:
// User Date
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.YYYY - HH:mm:ss");
String dateTimeUI = sdf.format(new Date());
System.out.println("UI: " + dateTimeUI);
labelDatumZeit.setText(dateTimeUI);
System.out.println("[UI]: " + dateTimeUI);
// SQL-Date
SimpleDateFormat sdf2 = new SimpleDateFormat("dd.MM.YYYY - HH:mm:ss");
Date d = sdf2.parse(dateTimeUI);
sdf2.applyPattern("yyyy-MM-dd HH:mm:ss");
dateTimeSQL = sdf2.format(d);
System.out.println("[SQL]: " + dateTimeSQL);
After converting to the new format my Data always is 2012-12-31 (+ correct time). Why is that?

YYYY is the week year. yyyy is the year. If you expect both to be the same thing, then that's where the problem is.
From the javadoc:
A week year is in sync with a WEEK_OF_YEAR cycle. All weeks between the first and last weeks (inclusive) have the same week year value. Therefore, the first and last days of a week year may have different calendar year values.
For example, January 1, 1998 is a Thursday. If getFirstDayOfWeek() is MONDAY and getMinimalDaysInFirstWeek() is 4 (ISO 8601 standard compatible setting), then week 1 of 1998 starts on December 29, 1997, and ends on January 4, 1998. The week year is 1998 for the last three days of calendar year 1997. If, however, getFirstDayOfWeek() is SUNDAY, then week 1 of 1998 starts on January 4, 1998, and ends on January 10, 1998; the first three days of 1998 then are part of week 53 of 1997 and their week year is 1997.
You want to use yyyy in both format.

Your problem is that in second format you use yyyy instead of YYYY.

Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.YYYY - HH:mm:ss");
String dateTimeUI = sdf.format(date);
System.out.println("UI: " + dateTimeUI);
// SQL-Date
Calendar calendar = sdf.getCalendar();
calendar.setTime(date);
System.out.println(calendar.getTime());
sdf.applyPattern("YYYY-MM-dd HH:mm:ss");
String dateTimeSQL = sdf.format(calendar.getTime());
System.out.println("[SQL]: " + dateTimeSQL);

Related

Getting the date as per the format in which month name is coming as first

I am getting the string in this formatas shown below
03-12-2018
I want to convert this into as below format as per Java 8 standards please advise
December 03 , 2018
what I have tried is shown below but i was not succeessful , please advise how to acheieve the same
SimpleDateFormat month_date = new SimpleDateFormat("MMM yyyy", Locale.ENGLISH);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String actualDate = "03-12-2018";
Date date = sdf.parse(actualDate);
String month_name = month_date.format(date);
System.out.println("Month :" + month_name);
java.time
DateTimeFormatter originalFormatter = DateTimeFormatter.ofPattern("dd-MM-uuuu");
DateTimeFormatter monthFirst = DateTimeFormatter
.ofLocalizedDate(FormatStyle.LONG)
.withLocale(Locale.ENGLISH);
String actualDate = "03-12-2018";
LocalDate date = LocalDate.parse(actualDate, originalFormatter);
String monthName = date.format(monthFirst);
System.out.println("Month :" + monthName);
Output:
Month :December 3, 2018
Since you are using Java 8 (and even if you didn’t), avoid the long outdated and notoriously troublesome SimpleDateFormat class. Use the built in formats where you can rather than rolling your own.
What went wrong in your code?
You parsed a string of 03-12-2018 with a format of yyyy-MM-dd. So this parses into the 2018th day of the 12th month of year 3 CE (2015 years ago). There obviously weren’t 2018 days in December. So it would have been fair to expect an exception. This is just one of the points where SimpleDateFormat is troublesome: with standard settings it just keeps counting days into the following months and years and ends up at June 9 year 9, that is, 5 and a half years later. Next you formatted this date with a formatter including month name and year, it seems you had forgot the day of month. Anyway it printed as Jun 0009 (which you should have told us in your question so that we could see what was wrong; this information can be very helpful in trying to solve your problem).
Link
Oracle tutorial: Date Time explaining how to use java.time.
It's just a matter of choosing the correct format (and applying a correct Locale):
DateTimeFormatter f = DateTimeFormatter.ofPattern("LLLL dd, yyyy");
System.out.println(f.format(yourDate));
Btw it's in the documentation:
...
Number/Text: If the count of pattern letters is 3 or greater, use the Text rules above. Otherwise use the Number rules above.
...
Use the following code:
SimpleDateFormat month_date = new SimpleDateFormat("MMMM dd, yyyy", Locale.ENGLISH);
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
String actualDate = "03-12-2018";
Date date = sdf.parse(actualDate);
String month_name = month_date.format(date);
System.out.println("Month :" + month_name);

Is there a built in function (Java) for an Android app to get the date range of the week of the current date ("today") [duplicate]

I want to get the last and the first week of a week for a given date.
e.g if the date is 12th October 2011 then I need the dates 10th October 2011 (as the starting date of the week) and 16th october 2011 (as the end date of the week)
Does anyone know how to get these 2 dates using the calender class (java.util.Calendar)
thanks a lot!
Some code how to do it with the Calendar object. I should also mention joda time library as it can help you many of Date/Calendar problems.
Code
public static void main(String[] args) {
// set the date
Calendar cal = Calendar.getInstance();
cal.set(2011, 10 - 1, 12);
// "calculate" the start date of the week
Calendar first = (Calendar) cal.clone();
first.add(Calendar.DAY_OF_WEEK,
first.getFirstDayOfWeek() - first.get(Calendar.DAY_OF_WEEK));
// and add six days to the end date
Calendar last = (Calendar) first.clone();
last.add(Calendar.DAY_OF_YEAR, 6);
// print the result
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(df.format(first.getTime()) + " -> " +
df.format(last.getTime()));
}
This solution works for any locale (first day of week could be Sunday or Monday).
Date date = new Date();
Calendar c = Calendar.getInstance();
c.setTime(date);
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK) - c.getFirstDayOfWeek();
c.add(Calendar.DAY_OF_MONTH, -dayOfWeek);
Date weekStart = c.getTime();
// we do not need the same day a week after, that's why use 6, not 7
c.add(Calendar.DAY_OF_MONTH, 6);
Date weekEnd = c.getTime();
For example, today is Jan, 29 2014. For the locale with Sunday as a first day of week you will get:
start: 2014-01-26
end: 2014-02-01
For the locale with Monday as a first day the dates will be:
start: 2014-01-27
end: 2014-02-02
If you want all dates then
first.add(Calendar.DAY_OF_WEEK,first.getFirstDayOfWeek() - first.get(Calendar.DAY_OF_WEEK));
for (int i = 1; i <= 7; i++) {
System.out.println( i+" Day Of that Week is",""+first.getTime());
first.add(Calendar.DAY_OF_WEEK,1);
}
Here is the sample code
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
cal.set(2016, 2, 15);
{
Calendar startCal = Calendar.getInstance();
startCal.setTimeInMillis(cal.getTimeInMillis());
int dayOfWeek = startCal.get(Calendar.DAY_OF_WEEK);
startCal.set(Calendar.DAY_OF_MONTH,
(startCal.get(Calendar.DAY_OF_MONTH) - dayOfWeek) + 1);
System.out.println("end date : " + startCal.getTime());
}
{
Calendar endCal = Calendar.getInstance();
endCal.setTimeInMillis(cal.getTimeInMillis());
int dayOfWeek = endCal.get(Calendar.DAY_OF_WEEK);
endCal.set(Calendar.DAY_OF_MONTH, endCal.get(Calendar.DAY_OF_MONTH)
+ (7 - dayOfWeek));
System.out.println("start date : " + endCal.getTime());
}
}
which will print
start date : Sun Mar 13 20:30:30 IST 2016
end date : Sat Mar 19 20:30:30 IST 2016
I have found the formula in the accepted answer will only work in some cases. For example your week starts on Saturday and today is Sunday. To arrive at the first day of the week we walk back 1 day, but the formula cal.get(Calendar.DAY_OF_WEEK) - cal.getFirstDayOfWeek() will give the answer -6. The solution is to use a modulus so the formula wraps around so to speak.
int daysToMoveToStartOfWeek = (
7 +
cal.get(Calendar.DAY_OF_WEEK) -
cal.getFirstDayOfWeek()
)%7;
cal.add(Calendar.DAY_OF_WEEK, -1 * daysToMoveToStartOfWeek);

Getting the start and the end date of a week using java calendar class

I want to get the last and the first week of a week for a given date.
e.g if the date is 12th October 2011 then I need the dates 10th October 2011 (as the starting date of the week) and 16th october 2011 (as the end date of the week)
Does anyone know how to get these 2 dates using the calender class (java.util.Calendar)
thanks a lot!
Some code how to do it with the Calendar object. I should also mention joda time library as it can help you many of Date/Calendar problems.
Code
public static void main(String[] args) {
// set the date
Calendar cal = Calendar.getInstance();
cal.set(2011, 10 - 1, 12);
// "calculate" the start date of the week
Calendar first = (Calendar) cal.clone();
first.add(Calendar.DAY_OF_WEEK,
first.getFirstDayOfWeek() - first.get(Calendar.DAY_OF_WEEK));
// and add six days to the end date
Calendar last = (Calendar) first.clone();
last.add(Calendar.DAY_OF_YEAR, 6);
// print the result
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(df.format(first.getTime()) + " -> " +
df.format(last.getTime()));
}
This solution works for any locale (first day of week could be Sunday or Monday).
Date date = new Date();
Calendar c = Calendar.getInstance();
c.setTime(date);
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK) - c.getFirstDayOfWeek();
c.add(Calendar.DAY_OF_MONTH, -dayOfWeek);
Date weekStart = c.getTime();
// we do not need the same day a week after, that's why use 6, not 7
c.add(Calendar.DAY_OF_MONTH, 6);
Date weekEnd = c.getTime();
For example, today is Jan, 29 2014. For the locale with Sunday as a first day of week you will get:
start: 2014-01-26
end: 2014-02-01
For the locale with Monday as a first day the dates will be:
start: 2014-01-27
end: 2014-02-02
If you want all dates then
first.add(Calendar.DAY_OF_WEEK,first.getFirstDayOfWeek() - first.get(Calendar.DAY_OF_WEEK));
for (int i = 1; i <= 7; i++) {
System.out.println( i+" Day Of that Week is",""+first.getTime());
first.add(Calendar.DAY_OF_WEEK,1);
}
Here is the sample code
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
cal.set(2016, 2, 15);
{
Calendar startCal = Calendar.getInstance();
startCal.setTimeInMillis(cal.getTimeInMillis());
int dayOfWeek = startCal.get(Calendar.DAY_OF_WEEK);
startCal.set(Calendar.DAY_OF_MONTH,
(startCal.get(Calendar.DAY_OF_MONTH) - dayOfWeek) + 1);
System.out.println("end date : " + startCal.getTime());
}
{
Calendar endCal = Calendar.getInstance();
endCal.setTimeInMillis(cal.getTimeInMillis());
int dayOfWeek = endCal.get(Calendar.DAY_OF_WEEK);
endCal.set(Calendar.DAY_OF_MONTH, endCal.get(Calendar.DAY_OF_MONTH)
+ (7 - dayOfWeek));
System.out.println("start date : " + endCal.getTime());
}
}
which will print
start date : Sun Mar 13 20:30:30 IST 2016
end date : Sat Mar 19 20:30:30 IST 2016
I have found the formula in the accepted answer will only work in some cases. For example your week starts on Saturday and today is Sunday. To arrive at the first day of the week we walk back 1 day, but the formula cal.get(Calendar.DAY_OF_WEEK) - cal.getFirstDayOfWeek() will give the answer -6. The solution is to use a modulus so the formula wraps around so to speak.
int daysToMoveToStartOfWeek = (
7 +
cal.get(Calendar.DAY_OF_WEEK) -
cal.getFirstDayOfWeek()
)%7;
cal.add(Calendar.DAY_OF_WEEK, -1 * daysToMoveToStartOfWeek);

Challenging Java/Groovy Date Manipulation

I have a bunch of dates formatted with the year and week, as follows:
2011-10
The week value is the week of the year(so 1-52). From this week value, I need to output something like the following:
Mar 7
Explicitly, I need the Month that the given week is in, and the date of the first Monday of that week. So in other words it is saying that the 10th week of the year is the week of March 7th.
I am using Groovy. What kind of date manipulation can I do to get this to work?
Here's a groovy solution:
use(groovy.time.TimeCategory) {
def (y, w) = "2011-10".tokenize("-")
w = ((w as int) + 1) as String
def d = Date.parse("yyyy-w", "$y-$w") + 1.day
println d.format("MMM dd")
}
Use a GregorianCalendar (or Joda, if you don't mind a dependency)
String date = "2011-10";
String[] parts = date.split("-");
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, Integer.parseInt(parts[0]));
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
cal.set(Calendar.WEEK_OF_YEAR, Integer.parseInt(parts[1])+1);
DateFormat df = new SimpleDateFormat("MMM d");
System.out.println(df.format(cal.getTime()) + " (" + cal.getTime() + ")");
EDIT: Added +1 to week, since calendar uses zero-based week numbers
Date date = new SimpleDateFormat("yyyy-w", Locale.UK).parse("2011-10");
System.out.println(new SimpleDateFormat("MMM d").format(date));
The first line returns first day of the 10th week in British Locale (March 7th). When Locale is not enforced, the results are dependent on default JVM Locale.
Formats are explained here.
You can use SimpleDateFormat, just like in java. See groovyconsole.appspot.com/script/439001
java.text.DateFormat df = new java.text.SimpleDateFormat('yyyy-w', new Locale('yourlocale'))
Date date = df.parse('2011-10')
To add a week, simply use Date date = df.parse('2011-10')+7
You don't need to set the Locale if your default Locale is using Monday as the first day of week.

Java - How to calculate the first and last day of each week

I'm trying to create a weekly calendar that looks like this: http://dhtmlx.com/docs/products/dhtmlxScheduler/sample_basic.html
How can I calculate every week date? For example, this week is:
Monday - Sunday
7 June, 8 June, 9 June, 10 June, 11 June, 12 June, 13 June
I guess this does what you want:
// Get calendar set to current date and time
Calendar c = Calendar.getInstance();
// Set the calendar to monday of the current week
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
// Print dates of the current week starting on Monday
DateFormat df = new SimpleDateFormat("EEE dd/MM/yyyy");
for (int i = 0; i < 7; i++) {
System.out.println(df.format(c.getTime()));
c.add(Calendar.DATE, 1);
}
With the new date and time API in Java 8 you would do:
LocalDate now = LocalDate.now();
// determine country (Locale) specific first day of current week
DayOfWeek firstDayOfWeek = WeekFields.of(Locale.getDefault()).getFirstDayOfWeek();
LocalDate startOfCurrentWeek = now.with(TemporalAdjusters.previousOrSame(firstDayOfWeek));
// determine last day of current week
DayOfWeek lastDayOfWeek = firstDayOfWeek.plus(6); // or minus(1)
LocalDate endOfWeek = now.with(TemporalAdjusters.nextOrSame(lastDayOfWeek));
// Print the dates of the current week
LocalDate printDate = startOfCurrentWeek;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE dd/MM/yyyy");
for (int i=0; i < 7; i++) {
System.out.println(printDate.format(formatter));
printDate = printDate.plusDays(1);
}
Java.time
Using java.time library built into Java 8:
import java.time.DayOfWeek;
import java.time.LocalDate;
import static java.time.temporal.TemporalAdjusters.previousOrSame;
import static java.time.temporal.TemporalAdjusters.nextOrSame;
LocalDate now = LocalDate.now(); # 2015-11-23
LocalDate first = now.with(previousOrSame(DayOfWeek.MONDAY)); # 2015-11-23
LocalDate last = now.with(nextOrSame(DayOfWeek.SUNDAY)); # 2015-11-29
You can iterate over DayOfWeek.values() to get all current week days
DayOfWeek.values(); # Array(MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY)
for (DayOfWeek day: DayOfWeek.values()) {
System.out.print(first.with(nextOrSame(day)));
} # 2015-11-23, 2015-11-24, 2015-11-25, 2015-11-26, 2015-11-27, 2015-11-28, 2015-11-29
First day of this week.
Calendar c = Calendar.getInstance();
while (c.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
c.add(Calendar.DATE, -1);
}
Simply setting the day of week does not seem to be reliable. Consider the following simple code:
Calendar calendar = Calendar.getInstance(Locale.GERMANY);
calendar.set(2011, Calendar.SEPTEMBER, 18);
System.out.printf("Starting day: %tF%n", calendar);
calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.printf("Last monday: %tF%n", calendar);
System.out.printf("First day of week: %d%n", calendar.getFirstDayOfWeek());
The result of running this program is:
Starting day: 2011-09-18
Last monday: 2011-09-19
First day of week: 2
In other words, it stepped forward in time. For a German locale, this is really not the expected answer. Note that the calendar correctly uses Monday as first day of the week (only for computing the week of the year, perhaps).
You can build up on this: The following code prints the first and last dates of each week for 15 weeks from now.
Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
for(int i=0; i<15; i++)
{
System.out.print("Start Date : " + c.getTime() + ", ");
c.add(Calendar.DAY_OF_WEEK, 6);
System.out.println("End Date : " + c.getTime());
c.add(Calendar.DAY_OF_WEEK, 1);
}
If you know which day it is (Friday) and the current date (June 11), you can calculate the other days in this week.
I recommend that you use Joda Time library. Gregorian Calendar class has weekOfWeekyear and dayOfWeek methods.
Calendar startCal = Calendar.getInstance();
startCal.setTimeInMillis(startDate);
Calendar endCal = Calendar.getInstance();
endCal.setTimeInMillis(endDate);
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMMM-yyyy");
while (startCal.before(endCal)) {
int weekNumber = startCal.get(Calendar.WEEK_OF_YEAR);
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
cal.set(Calendar.WEEK_OF_YEAR, weekNumber);
Date sunday = cal.getTime();
Log.d("sunday", "" + sdf.format(sunday));
cal.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
cal.set(Calendar.WEEK_OF_YEAR, weekNumber);
Date saturday = cal.getTime();
Log.d("saturday", "" + sdf.format(saturday));
weekNumber = weekNumber + 1;
startCal.set(Calendar.WEEK_OF_YEAR, weekNumber);
}
Yes. Use Joda Time
http://joda-time.sourceforge.net/
The algorithm you're looking for (calculating the day of the week for any given date) is "Zeller's Congruence". Here's a Java implementation:
http://technojeeves.com/joomla/index.php/free/57-zellers-congruence

Categories