I have one problem with android calendar programming, so
If there are 2 months on one week, android write me name of old month. I want him to write something like (old month-new month).
My Code is as follows
Calendar wek = Calendar.getInstance(Locale.US);
wek.add(Calendar.WEEK_OF_YEAR,r);
SimpleDateFormat gm = new SimpleDateFormat("MMM yyy");
mes.setText(gm.format(wek.getTime()));
The reason it does this is because when looking at a date represented by a week, it only looks at the first day in the week. You'd need to manually check first and last days of the week and, if they are in a different month, then format the date manually. You also need to be careful about the week overlapping the years as well. Something like this:
Calendar wek = Calendar.getInstance(Locale.US);
wek.add(Calendar.WEEK_OF_YEAR,r);
//this will set your calendar onto the first day of the week
int w = wek.get(Calendar.WEEK_OF_YEAR);
int y = wek.get(Calendar.YEAR);
wek.clear();
wek.set(Calendar.YEAR, y);
wek.set(Calendar.WEEK_OF_YEAR, w);
//get the month and year of the first day of the week
int m1 = wek1.get(Calendar.MONTH);
int y1 = wek1.get(Calendar.YEAR);
//get the date for the end of the week and its month and year
Calendar w2 = wek;
w2.add(Calendar.DATE, 6);
int m2 = w2.get(Calendar.MONTH);
int y2 = w2.get(Calendar.YEAR);
if(m1 == m2) {
//if the two months are the same, then just format the date
SimpleDateFormat gm = new SimpleDateFormat("MMM yyyy");
mes.setText(gm.format(wek.getTime()));
}
else if(y1 == y1) {
//different months, same year - format as "MMM - MMM yyyy"
SimpleDateFormat gm = new SimpleDateFormat("MMM");
SimpleDateFormat gy = new SimpleDateFormat("yyyy");
mes.setTextText(gm.format(wek.getTime()) + " - " +
gm.format(w2.getTime()) + " " +
gy.format(wek.getTime()));
}
else {
//Different months and different years - format as "MMM yyyy - MMM yyyy"
SimpleDateFormat gm = new SimpleDateFormat("MMM yyyy");
mes.setTextText(gm.format(wek.getTime()) + " - " +
gm.format(w2.getTime()));
}
And what is the correct month you think? What you do is add r weeks to the exact moment of now. This is specific point in time and is associated with particular millisecond. This millisecond belongs either to one or the other month. And your code returns which month is that.
You should get the index of the first day of week, and the last one and check the month they belong to.
(I am not a native speaker but you could say that a week overlaps two months, more than a week on 2 months.)
Related
This question already has answers here:
Change date format in a Java string
(22 answers)
Closed 5 years ago.
Hi I am trying to get today's date but not getting proper output
import java.text.DateFormat;
import java.text.SimpleDateFormat;
private static final DateFormat sdf = new SimpleDateFormat("DD/MM/YYYY");
System.out.println("TODAY :" + sdf.format(new Date()));
output
TODAY :142/05/2017
Year and month coming properly but why the day is coming like this
D is Day in year
d is Day in month
http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
EDIT: Also as #JeremyP noticed you can use yyyyfor getting year 'cause
Y is Week year
Oracle:
SimpleDateFormat is a concrete class for formatting and parsing dates
in a locale-sensitive manner. It allows for formatting (date -> text),
parsing (text -> date), and normalization.
simple y Year -Year (1996; 96)
capital Y Week year -Year (2009; 09)
simple d Day in month -Number (10)
capital D Day in year -Number (189)
capital M Month in year -Month (July; Jul; 07)
In your code:
SimpleDateFormat("DD/MM/YYYY")
Should be:
SimpleDateFormat("dd/MM/yyyy")
refer documentation for more info
According to the javadocs
D is for the day in the year and Y is for the week year.
You need to use d (lower case) for Day in month and y (lower case) for Year
This you pattern should look like:
DateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Replace DD with dd and YYYY to yyyy. MM is in capital and others are in lowercase.
d = day of the month
D = day of the year
M = month in year
m = minute in hour
y = Year
Y = Week year
private static final DateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
System.out.println("TODAY :" + sdf.format(new Date()));
I have an application that plugs into the Google Fit Api and returns the steps for the last 7 days, the method is below. As the screen shot shows though I wish to add the day to the step count.
I have tried many options to take away one day at a time for the 7 loop but had no luck, it just says the same day. Any help would be great thank you.
private void dumpDataSet(DataSet dataSet) {
Log.i(TAG, "Data returned for Data type: " + dataSet.getDataType().getName());
DateFormat dateFormat = DateFormat.getTimeInstance();
int i = 0;
for (DataPoint dp : dataSet.getDataPoints()) {
for(Field field : dp.getDataType().getFields()) { //loop 7 times
int test = dp.getValue(field).asInt();
String weekSteps= String.valueOf(test); //get weekday steps one at a time
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Calendar cal = Calendar.getInstance();
String weekday = sdf.format(cal.getTime());
String weekStepsFinal= weekSteps + " steps on " + weekday; //set Textfield to steps and the day
FeedItem item = new FeedItem();
item.setTitle(weekStepsFinal);
feedItemList.add(item);
}
}
}
There are 7 datasets btw.
If by "take away one day at a time" means that you want the days going backwards, then here's how:
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
System.out.println("Last 7 days (starting today):");
Calendar cal = Calendar.getInstance(); // Initialized to today/now
for (int i = 0; i < 7; i++) {
System.out.println(" " + sdf.format(cal.getTime()));
cal.add(Calendar.DAY_OF_MONTH, -1); // Update to previous day at same time-of-day
}
OUTPUT
Last 7 days (starting today):
Monday
Sunday
Saturday
Friday
Thursday
Wednesday
Tuesday
This will subtract 7 days from the calendar to get you the date 7 days ago:
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH, -7).
To subtract one day use the following code :
int DAY_IN_MILLIS = 1000 * 60 * 60 * 24;
Date currentDate = new Date();
long previousDay = currentDate.getTime()-DAY_IN_MILLIS;
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
String day = sdf.format(previousDay);
I have to put a date one week before and then 1 month before. If i try with the days one week before is working but if the day es 5 and it has to change the month is not working, it changes me the year instead. About the month it changes me the year
tring addUrl = "";
SimpleDateFormat sdf = new SimpleDateFormat("dd.mm.yyyy");
// surround below line with try catch block as below code throws checked
// exception
Date endDate = sdf.parse(request.getParameter(field.getId()));
Calendar cal = DateToCalendar(endDate);
cal.setTime(endDate);
SimpleDateFormat formatToSend = new SimpleDateFormat("yyy-mm-dd");
case "day":
cal.add(Calendar.DATE, -1);
addUrl = "startDate=" + formatToSend.format(cal.getTime()) + "&endDate=" + endDateString;
break;
case "week":
cal.add(Calendar.DATE, -6); // number of days to add
addUrl = "startDate=" + formatToSend.format(cal.getTime()) + "&endDate=" + endDateString;
break;
default:
cal.add(Calendar.MONTH, -1); // number of days to add
addUrl = "startDate=" + formatToSend.format(cal.getTime()) + "&endDate=" + endDateString;
}
How i can do that?
Thanks
In your SimpleDateFormat objects, you should use MM for months and not mm, because mm means minutes, not months.
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
SimpleDateFormat formatToSend = new SimpleDateFormat("yyyy-MM-dd");
See the API documentation of java.text.SimpleDateFormat.
Im not sure do i fully understand the question however one potential problem is in your date format
m = Minute in hour
M = Month in year <- maybe the one you want?
See here for more examples.
https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
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);
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.