I have a problem to sort date because of the format of these dates.
I obtain the date :
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
And I build a String with these values.
dateRappDB = (new StringBuilder()
.append(mYear).append(".")
.append(mMonth + 1).append(".")
.append(mDay).append(" ")).toString();
The problem is that if the month is for example February, mMonth value is 2. So dates with months like October (10) comes before in my list.
What I need is that month and day are formated like MM and dd. But I don't know how to do it in my case.
EDIT :
I solved the problem by using a DateFormat like said above.
I replaced this :
dateRappDB = (new StringBuilder()
.append(mYear).append(".")
.append(mMonth + 1).append(".")
.append(mDay).append(" ")).toString();
By this :
Date date = new Date(mYear - 1900, mMonth, mDay);
dateFacDB = DateFormat.format("yyyy.MM.dd", date).toString();
And it works.
Thanks to all of you for your help :)
here is a simple way to convert Date to String :
SimpleDateFormat simpleDate = new SimpleDateFormat("dd/MM/yyyy");
String strDt = simpleDate.format(dt);
Calendar calendar = Calendar.getInstance();
Date now = calendar.getTime();
String timestamp = simpleDateFormat.format(now);
These might come in handy
SimpleDateFormat simpleDateFormat =
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSZZZZZ");
this format is equal to --> "2016-01-01T09:30:00.000000+01:00"
SimpleDateFormat simpleDateFormat =
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZZZZ");
this format is equal to --> "2016-06-01T09:30:00+01:00"
here is the example for date format
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date date = new Date();
System.out.println("format 1 " + sdf.format(date));
sdf.applyPattern("E MMM dd yyyy");
System.out.println("format 2 " + sdf.format(date));
You need to sort dates, not strings. Also, have you heared about DateFormat? It makes all that appends for you.
If I understand your issue, you create a list of dates and since they're strings, they get arranged in a dictionary-order number-wise, which means you get october before february (10 before 2).
If I were you, I would store my results in a container where I control the insertion point (like an array list) or where I can control the sorting algorithm.
Related
I want to compare two date objects like this:
String format = "MM/dd/yyyy hh:mm a";
SimpleDateFormat sdf = new SimpleDateFormat(format);
fakeDate = sdf.parse("15/07/2013 11:00 AM");
fakeDate2 = sdf.parse("15/07/2013 12:00 AM");
int diff = date2.getHours() - date1.getHours();
but then I see getHours is deprecated.
So i have used:
Calendar calendar1 = Calendar.getInstance();
calendar.setTime(new Date("15/7/2013 11:00AM"));
Calendar calendar2 = Calendar.getInstance();
calendar.setTime(new Date("11/7/2013 12:00AM"));
calendar1.get(Calendar.HOUR_OF_DAY) - calendar2.get(Calendar.HOUR_OF_DAY)
but then I see the diff is zero. I guess i change the same calendar instance all the time and compare it to itself. no?
how would you write this?
new Date("15/7/2013 11:00AM")
is not the correct way to construct a Date object. It's deprecated also. Use proper SimpleDateFormat as you are doing well in your first example.
The format MM/dd/yyyy hh:mm a is not correct as per the input date string.
It should be like this.
String format = "dd/MM/yyyy hh:mm a";
SimpleDateFormat sdf = new SimpleDateFormat(format);
Date fakeDate = sdf.parse("15/07/2013 11:00 AM");
Date fakeDate2 = sdf.parse("15/07/2013 12:00 AM");
Calendar cal = Calendar.getInstance();
cal.setTime(fakeDate); //set time to first date
int hours1 = cal.get(Calendar.HOUR); // get the hours
cal.setTime(fakeDate2); // set time to second date
int hours2 = cal.get(Calendar.HOUR); // get the hours
System.out.println(hours1 - hours2); // 11 hours
You seemed really confused though it is depreciated this code shall give you a difference of 11 hours which makes sense
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm a");
Date fakeDate = dateFormat.parse("15/07/2013 11:00 AM");
Date fakeDate2 = dateFormat.parse("15/07/2013 12:00 AM");
System.out.println(fakeDate.getHours()-fakeDate2.getHours());
Or if you are so interested to use Calendar do it this way
Calendar calendar = Calendar.getInstance();
calendar.setTime(fakeDate);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(fakeDate2);
System.out.println(calendar.get(Calendar.HOUR_OF_DAY) -
calendar2.get(Calendar.HOUR_OF_DAY));
You will get the same 11 hours difference or simply do it this way
long millisForNewDate = toDate.getTime();
long millisForOldDate = fromDate.getTime();
long difference = millisForNewDate - millisForOldDate;
int hoursDifferenceBetweenDates = (int)(difference/(1000*60*60));
How do I create a function which take current date and return month name?
I have only date its not current date it can be any date like 2013/4/12 or 23/8/8.
Like String monthName("2013/9/11");
when call this function return the month name.
This should be fine.
It depends on the format of date.
If you try with February 1, 2011
it would work, just change this string "MMMM d, yyyy" according to your needs.
Check this for all format patterns.
And also, months are 0 based, so if you want January to be 1, just return month + 1
private static int getMonth(String date) throws ParseException{
Date d = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH).parse(date);
Calendar cal = Calendar.getInstance();
cal.setTime(d);
int month = cal.get(Calendar.MONTH);
return month + 1;
}
If you want month name try this
private static String getMonth(String date) throws ParseException{
Date d = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH).parse(date);
Calendar cal = Calendar.getInstance();
cal.setTime(d);
String monthName = new SimpleDateFormat("MMMM").format(cal.getTime());
return monthName;
}
As I said, check web page I posted for all format patterns. If you want only 3 characters of month, use "MMM" instead of "MMMM"
java.time
I am contributing the modern answer.
System.out.println(LocalDate.of(2013, Month.SEPTEMBER, 11) // Define the date
.getMonth() // Get the month
.getDisplayName( // Get the month name
TextStyle.FULL_STANDALONE, // No abbreviation
Locale.ENGLISH)); // In which language?
Output is:
September
Use LocalDate from java.time, the modern Java date and time API, for a date.
Use LocalDate.getMonth() and Month.getDisplayName() to get the month name.
Avoid Date, Calendar and SimpleDateFormat used in the old answers from 2013. Those classes are poorly designed, troublesome and long outdated. The modern API is so much nicer to work with. Also avoid switch/case for this purpose since the month names are already built in, and using the library methods gives you clearer, terser and less error-prone code.
Use LocalDate
LocalDate today = LocalDate.now(ZoneId.systemDefault());
LocalDate aDate = LocalDate.of(2013, Month.SEPTEMBER, 11); // 2013/9/11
LocalDate anotherDate = LocalDate.of(2023, 8, 8); // 23/8/8
If you are getting the date as string input, parse the string using a DateTimeFormatter:
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("u/M/d");
String stringInput = "2013/4/12";
LocalDate date = LocalDate.parse(stringInput, dateFormatter);
System.out.println(date);
2013-04-12
Use LocalDate.getMonth() and Month.getDisplayName()
To get the month name you first need to decide in which language you want the month name. I am taking English as an example and still using date from the previous snippet:
String monthName = date.getMonth()
.getDisplayName(TextStyle.FULL_STANDALONE, Locale.ENGLISH);
System.out.println(monthName);
April
Java knows the month names in a wealth of languages. If you want the month name in the user’s language, pass Locale.getDefault() as the second argument to getDisplayName().
Link
Oracle tutorial: Date Time explaining how to use java.time.
Use this code -
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
int month = calendar.get(Calendar.MONTH);
So now you have month number, you can use switch case to get name for that month.
If your date is in string format use this-
Date date = new SimpleDateFormat("yyyy-MM-dd").format(d)
Simple solution to get current month by name:
SimpleDateFormat formatterMonth = new SimpleDateFormat("MMMM");
String currentMonth = formatterMonth.format(new Date(System.currentTimeMillis()));
Function to get any month by name using format 2013/9/11: (not tested)
private String monthName(String dateToCheck){
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
date = formatter.parse(dateToCheck);
SimpleDateFormat formatterMonth = new SimpleDateFormat("MMMM");
return formatterMonth.format(new Date(date.getTime()));
}
I am using a function like this:
public String getDate(String startDate) throws ParseException {
#SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date d = null;
try {
d = sdf.parse(startDate);
sdf.applyPattern("MMMM dd, YYYY"); //this gives output as=> "Month date, year"
} catch (Exception e) {
Log.d("Exception", e.getLocalizedMessage());
}
return sdf.format(d);
}
You can obtain the "number" of the month as described in the other answer and then you could simply use a switch to obtain a name.
Example:
switch(month) {
case 0:
your name is January
break;
...
}
P.S. I think months are zero-based but I'm not 100% sure...
I have created a web service which returns the date of an event which is initially captured by the getDate() function. I want the date returned by this function (something along this format : 2013-05-17 14:52:00.943) to be parsed and shown to the user in the DD-MM-YYYY format.
Any suggestions? I haven't found any solution along this direction yet.
I have tried this code and it's work fine for me,Please Try my code below: Please upvote to Tarun also coz he gave almost right answer.just he did mistake that he passes cal.getTime() method instead of pDate
String formatDate = p.format(pDate);
and second mistake in format like"DD-MM-YYYY" but actual format is:
"dd-MM-yyyy" not "DD-MM-YYYY"
I have done changes in it and modify it.
String dateStr = "2013-05-16 14:52:00.943";
SimpleDateFormat c = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.S"); // your web service format
Date pDate = c.parse(dateStr);
SimpleDateFormat p = new SimpleDateFormat("dd-MM-yyyy"); // your required format
String formatDate = p.format(pDate); // convert it in your required format
SimpleDateFormat formatter = new SimpleDateFormat("EEEE"); // Day format as you want EEE for like "Sat" and EEEE for like "Saturday"
String Day = formatter.format(pDate); // This will give you a day as your selected format
System.out.println("Date & Day>>>"+formatDate+" "+Day);
// For GMT format your format should be like this: "2013-05-16 14:52:00.943 GMT+05:30"
// Give it to me in GMT time.
c.setTimeZone(TimeZone.getTimeZone("GMT+05:30"));
System.out.println("GMT time: " + c.format(pDate));
Output:
Date & Day>>>16-05-2013 Thursday
GMT time: 2013-05-16 02:52:00.943 Greenwich Mean Time
Joda time:
you can download 2.0 jar file of joda time from here:
DateTimeFormatter jodaFormatter = ISODateTimeFormat.dateTime();
DateTime jodaParsed = jodaFormatter
.parseDateTime("2013-05-17T16:27:34.9+05:30");
Date date2 = jodaParsed.toDate();
System.out.println("Date & Day:" + jodaParsed.getDayOfMonth() + "-" + jodaParsed.getMonthOfYear() + "-" + jodaParsed.getYear() + " " + jodaParsed.getHourOfDay() + ":" + jodaParsed.getMinuteOfHour()+" "+jodaParsed.dayOfWeek().getAsText());
output:
Date & Day:17-5-2013 16:27 Friday
Hope it will work for you.
String dateStr = "2013-05-17 14:52:00.943";
SimpleDateFormat c = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.S");
Date pDate = c.parse(dateStr);
SimpleDateFormat p = new SimpleDateFormat("dd-MM-yyyy");
String formatDate = p.format(pDate);
You can use Joda Time if you have colon in time offset.
DateTimeFormatter jodaFormatter = ISODateTimeFormat.dateTime();
DateTime jodaParsed = jodaFormatter.parseDateTime("2013-05-17T16:27:34.9+05:30");
Date date = jodaParsed.toDate();
Calendar c = Calendar.getInstance();
c.setTime(date);
c.get(Calendar.DATE));
More info about joda can be found here.
Use a SimpleDateFormat to parse the date and then print it out with a SimpleDateFormat withe the desired format.
Example:
SimpleDateFormat format1 = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat format2 = new SimpleDateFormat("dd-MM-yyyy");
Date date = format1.parse("05/18/2013");
System.out.println(format2.format(date));
Output:
11-05-2013
Edit:
Calendar cal = Calendar.getInstance();
cal.setTime(specific_date);
int dayOfMonth = cal.get(Calendar.DAY_OF_WEEK);
String dayOfMonthStr = String.valueOf(dayOfMonth);
I want to do something like:
Date date = new Date(); // current date
date = date - 300; // substract 300 days from current date and I want to use this "date"
How to do it?
Java 8 and later
With Java 8's date time API change, Use LocalDate
LocalDate date = LocalDate.now().minusDays(300);
Similarly you can have
LocalDate date = someLocalDateInstance.minusDays(300);
Refer to https://stackoverflow.com/a/23885950/260990 for translation between java.util.Date <--> java.time.LocalDateTime
Date in = new Date();
LocalDateTime ldt = LocalDateTime.ofInstant(in.toInstant(), ZoneId.systemDefault());
Date out = Date.from(ldt.atZone(ZoneId.systemDefault()).toInstant());
Java 7 and earlier
Use Calendar's add() method
Calendar cal = Calendar.getInstance();
cal.setTime(dateInstance);
cal.add(Calendar.DATE, -30);
Date dateBefore30Days = cal.getTime();
#JigarJoshi it's the good answer, and of course also #Tim recommendation to use .joda-time.
I only want to add more possibilities to subtract days from a java.util.Date.
Apache-commons
One possibility is to use apache-commons-lang. You can do it using DateUtils as follows:
Date dateBefore30Days = DateUtils.addDays(new Date(),-30);
Of course add the commons-lang dependency to do only date subtract it's probably not a good options, however if you're already using commons-lang it's a good choice. There is also convenient methods to addYears,addMonths,addWeeks and so on, take a look at the api here.
Java 8
Another possibility is to take advantage of new LocalDate from Java 8 using minusDays(long days) method:
LocalDate dateBefore30Days = LocalDate.now(ZoneId.of("Europe/Paris")).minusDays(30);
Simply use this to get date before 300 days, replace 300 with your days:
Date date = new Date(); // Or where ever you get it from
Date daysAgo = new DateTime(date).minusDays(300).toDate();
Here,
DateTime is org.joda.time.DateTime;
Date is java.util.Date
Java 8 Time API:
Instant now = Instant.now(); //current date
Instant before = now.minus(Duration.ofDays(300));
Date dateBefore = Date.from(before);
As you can see HERE there is a lot of manipulation you can do. Here an example showing what you could do!
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
//Add one day to current date.
cal.add(Calendar.DATE, 1);
System.out.println(dateFormat.format(cal.getTime()));
//Substract one day to current date.
cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
System.out.println(dateFormat.format(cal.getTime()));
/* Can be Calendar.DATE or
* Calendar.MONTH, Calendar.YEAR, Calendar.HOUR, Calendar.SECOND
*/
With Java 8 it's really simple now:
LocalDate date = LocalDate.now().minusDays(300);
A great guide to the new api can be found here.
In Java 8 you can do this:
Instant inst = Instant.parse("2018-12-30T19:34:50.63Z");
// subtract 10 Days to Instant
Instant value = inst.minus(Period.ofDays(10));
// print result
System.out.println("Instant after subtracting Days: " + value);
I have created a function to make the task easier.
For 7 days after dateString: dateCalculate(dateString,"yyyy-MM-dd",7);
To get 7 days upto dateString: dateCalculate(dateString,"yyyy-MM-dd",-7);
public static String dateCalculate(String dateString, String dateFormat, int days) {
Calendar cal = Calendar.getInstance();
SimpleDateFormat s = new SimpleDateFormat(dateFormat);
try {
cal.setTime(s.parse(dateString));
} catch (ParseException e) {
e.printStackTrace();
}
cal.add(Calendar.DATE, days);
return s.format(cal.getTime());
}
You may also be able to use the Duration class. E.g.
Date currentDate = new Date();
Date oneDayFromCurrentDate = new Date(currentDate.getTime() - Duration.ofDays(1).toMillis());
You can easily subtract with calendar with SimpleDateFormat
public static String subtractDate(String time,int subtractDay) throws ParseException {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.ENGLISH);
cal.setTime(sdf.parse(time));
cal.add(Calendar.DATE,-subtractDay);
String wantedDate = sdf.format(cal.getTime());
Log.d("tag",wantedDate);
return wantedDate;
}
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.