So I have a Date object and I want to create a method so that it prints the Date in the following format:
11 September 2011, 9:15pm
How do I do that?
As of now I am just doing a toString to the date and it gives me all the GMT information and seconds precision that I don't need. Do I have to use a DateFormatter or is there an easier way to do this?
This was edited to include Java ME in the title and the tags after some of the answers that were correct for the original question were posted.
You may use SimpleDateFormat class to format your date.
http://download.oracle.com/javase/1,5.0/docs/api/java/text/SimpleDateFormat.html
I guess the pattern would be something like this:
SimpleDateFormat format = new SimpleDateFormat("dd MMMM yyyy, h:ma");
format.format(yourDate);
EDIT for Java ME;
I read that there is no SimpleDateFormat class in Java ME specs. So I would try Calendar;
First put your date to the Calendar, then get all you need. Better is make this a method
Calendar calendar = Calendar.getInstance();
Date myDate = new Date(); // as an example, date of "now"
calendar.setTime(myDate);
int day = calendar.get(Calendar.DAY_OF_MONTH);
int monthNumber = calendar.get(Calendar.MONTH);
String[] _months = new DateFormatSymbols().getMonths();
String[] months = new String[12];
for(int i =0; i < 12; i++){
months[i] = _months[i];
}
//because there is something wrong, we have a 12. month in the name of "" (nothing)
//or if there is no DateFormatSymbols class in your plans
//you may write for yourself;
/*
String[] monthNames = {"January", "February",
"March", "April", "May", "June", "July",
"August", "September", "October", "November",
"December"};
*/
String month = months[monthNumber]; //or String month = monthNames[monthNumber];
int year = calendar.get(Calendar.YEAR);
int hour = calendar.get(Calendar.HOUR);
int minute = calendar.get(Calendar.MINUTE);
String amPm = calendar.get(Calendar.AM_PM)==1 ? "am" : "pm";
System.out.println(day + " " + month + " " +
year + ", " + hour + ":" + minute + amPm);
Related
I have customer UI calendar I have an issue:
For example, September has 30 day start from 01/09/2020->30/09/2020 but UI calendar display from 29/08/2020->02/10/2020
This is my code. Who can help me?
val calendar: Calendar = Calendar.getInstance()
calendar.firstDayOfWeek = Calendar.MONDAY
calendar.add(Calendar.MONTH, position)
// Set day of month as 1
calendar.set(Calendar.DAY_OF_MONTH, 1)
// Get a number of the first day of the week
val dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK)
// Count when month is beginning
val firstDayOfWeek = calendar.firstDayOfWeek
val monthBeginningCell = (if (dayOfWeek < firstDayOfWeek) 7 else 0) + dayOfWeek - firstDayOfWeek
// Subtract a number of beginning days, it will let to load a part of a previous month
calendar.add(Calendar.DAY_OF_MONTH, -monthBeginningCell)
/* Get all days of one page (35 is a number of all possible cells in one page
(a part of previous month, current month and a part of next month))
*/
while (days.size < 35) {
days.add(calendar.time)
calendar.add(Calendar.DAY_OF_MONTH, 1)
}
What are exactly you need? If you need full range of calendar for one month, you can use below code for example:
class Scratch {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
// The month you want to set
int month = Calendar.SEPTEMBER;
calendar.set(Calendar.MONTH, month);
int firstDayOfMonth = calendar.getActualMinimum(Calendar.DAY_OF_MONTH);
int lastDayOfMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
System.out.println(getTimeOfWeek(lastDayOfMonth, false, month));
System.out.println(getTimeOfWeek(firstDayOfMonth, true, month));
}
private static Instant getTimeOfWeek(int day, boolean isFirst, int month) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, month);
calendar.set(Calendar.DAY_OF_MONTH, day);
int dayInWeek = calendar.get(Calendar.DAY_OF_WEEK);
if (isFirst) {
calendar.set(Calendar.DAY_OF_MONTH, day - dayInWeek + 1);
} else {
calendar.set(Calendar.DAY_OF_MONTH, day + 7 - dayInWeek);
}
return calendar.toInstant();
}
}
If you only want the range on the month, just set the calendar to the first and the last day on that month.
Hope it works!
I want to categorize values based on months so to filter those values required 1st & last date of last three months based on current month including current month values. Here how many last months is parameter. I wanted list of all months 1st date and last date. Any logic for the same will be helpful.
for example:-
// parameters
int lastMonths = 3;
date currentDate= 26-04-2019;
//expected output
current month is 04-2019 ,1st date is 1-04-2019 and last date is 30-04-2019
previous month is 03-2019, 1st date is 01-03-2019 and last date is 31-03-2019
previous month is 02-2019, 1st date is 01-02-2019 and last date is 28-02-2019
Use java.util.Calendar for addition and subraction in date
and
java.text.DateFormat to format date
DateFormat format = new SimpleDateFormat("dd-MM-yyyy", Locale.US);
DateFormat monthFormat = new SimpleDateFormat("MM-yyyy", Locale.US);
Calendar cal = Calendar.getInstance();
cal.setTime(format.parse("26-04-2019"));
for (int i = 0; i < 3; i++){
System.out.println("currentDate: " + monthFormat.format(cal.getTime())); // print current month
cal.set(Calendar.DAY_OF_MONTH, 1);
System.out.println("first date: " + format.format(cal.getTime())); // print first date
cal.add(Calendar.MONTH, 1);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.add(Calendar.DATE, -1);
System.out.println("last date: " + format.format(cal.getTime())); // print last date
cal.add(Calendar.MONTH, -1);
}
Important to say - there are tons of libraries who will give you this specific need, but I would like relying on one that does the work and was actually designed for (some of yours...) those use cases -
Java.time.LocalDate library (already built into Java 8)
import java.time.LocalDate;
LocalDate now = LocalDate.now(); // 2019-04-26
In order to get first and last days of month, you can use:
LocalDate start = YearMonth.now().atDay(1);
(now can be some other month, of course)
LocalDate end = YearMonth.now().atEndOfMonth();
You can use it specifically on one / two months, or with some for loop. Examples below:
1. Specific call:
LocalDate earlierOneMonth = now.minusMonths(1); // 2019-03-26
earlierOneMonth.getDay(); // 26
2. For Loop: (so you'll need something like an array / list to store those values...)
for(int i=0; i < lastMonths - 1; i++){
arr(i) = now.minusMonths(i + 1);
}
Also, in order to get the name of the month, you can use ->
earlierOneMonth.getMonth(); // APRIL
earlierOneMonth.getMonth.getValue(); // 04
Lastly, in order to get the year, you can use ->
earlier.getYear(); // 2019
Once you have all of your desired values, you can print them out as you requested, with that expected output:
"current month is" + nowMonth + "-" + nowYear + " ,1st date is" + nowDay + "-" + nowMonth + "-" + nowYear + " and last date is ...
Let me know if it's clear enough :)
tl;dr
YearMonth.now().minusMonths( 3 ).atDay( 1 ) // Get the first day of the month of three months ago. Returns `LocalDate` object.
YearMonth.now().minusMonths( 3 ).atEndOfMonth() // Get the last day of the month of three months ago. Returns `LocalDate` object.
YearMonth
You really care about the months. The dates are secondary. So focus on the months. Java has a class for that!
The YearMonth class represents a particular month of a particular year.
ZoneId z = ZoneId.of( "America/Edmonton" ) ;
YearMonth currentYm = YearMonth.now( z ) ;
Collect your months of interest.
List< YearMonth > yms = new ArrayList<>() ;
int limit = 3 ; // We want current month plus three previous months.
for( int i = 0 ; i <= limit ; i ++ ) {
YearMonth ym = currentYm.minusMonths( i ) ;
yms.add( ym ) ;
}
When you need dates, loop the list. Let YearMonth determine the first and last days of the month.
for( YearMonth ym : yms ) {
System.out.println( "YearMonth: " + ym + " starts: " + ym.atDay( 1 ) + " ends: " + ym.atEndOfMonth() ) ;
}
See this code run live at IdeOne.com.
YearMonth: 2019-04 starts: 2019-04-01 ends: 2019-04-30
YearMonth: 2019-03 starts: 2019-03-01 ends: 2019-03-31
YearMonth: 2019-02 starts: 2019-02-01 ends: 2019-02-28
YearMonth: 2019-01 starts: 2019-01-01 ends: 2019-01-31
If you need a Date object then the following will do just fine
Date date = getDate(targetDate);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.MONTH, -3);
calendar.set(Calendar.DAY_OF_MONTH, 1);
// calendar.getTime()
// The line above returns Date object
If you need a plain String then you can format it any way you want by simply using DateTimeFormatter from org.joda.time library and just use it's print() method on calendar.getTimeInMillis().
LocalDate currentDate = LocalDate.of(2019, 4, 26);//current date
System.out.println(currentDate);
int lastMonths = 3;//number of months
LocalDate prevDate = null;
LocalDate start = null;
LocalDate end = null;
for(int i = 0; i < lastMonths; i++) {
if(prevDate == null) {
start = currentDate.withDayOfMonth(1);//First day of current month
end = currentDate.withDayOfMonth(currentDate.lengthOfMonth());//Last day of current month
prevDate = currentDate.minusMonths(1);//subtracting one month from current month
} else {
start = prevDate.withDayOfMonth(1);//First day of previous month
end = prevDate.withDayOfMonth(prevDate.lengthOfMonth());//Last day of previous month
prevDate = prevDate.minusMonths(1);//subtracting one month from previous month
}
System.out.println(start + " " + end);
}
Output:
2019-04-26
2019-04-01 2019-04-30
2019-03-01 2019-03-31
2019-02-01 2019-02-28
Reference:
Get first and last day of month using threeten, LocalDate
int lastMonths = 3;
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1;
int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
DateFormat monthYearFormat = new SimpleDateFormat("MM-yyyy");
for (int i = 0; i < lastMonths; i++) {
int monthOfYear = month - i;
// if month is january, reset couter and month
if(monthOfYear == 0) {
month = 13;
year -= 1;
i = 0;
continue;
}
// get last day of month (month length)
YearMonth yearMonth = YearMonth.of(year, monthOfYear);
int firstDay = 1;
int lastDay = yearMonth.lengthOfMonth();
// create date with given year, month and day
Date date = new GregorianCalendar(year, monthOfYear - 1, firstDay).getTime();
String monthAndYear = monthYearFormat.format(date);
String currentOrPrevious;
if (i == 0) {
currentOrPrevious = "current";
} else {
currentOrPrevious = "previous";
}
String output = String.format("%s month is %s, 1st date is %02d-%s and last date is %d-%s", currentOrPrevious, monthAndYear, firstDay, monthAndYear, lastDay, monthAndYear);
System.out.println(output);
}
Output:
current month is 04-2019, 1st date is 01-04-2019 and last date is 30-04-2019
previous month is 03-2019, 1st date is 01-03-2019 and last date is 31-03-2019
previous month is 02-2019, 1st date is 01-02-2019 and last date is 28-02-2019
I have an assignment for a class I'm taking in which I have to make a Java console application, and it involves asking the user for a date, parsing that date, and working out what day of the month that date starts on. I have to then print out a calendar to look like this:
Calendar for September 2016
Su Mo Tu We Th Fr Sa
- - - - 1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 -
I have the date, I have the number of the day that the date starts on, (eg. Day= 1 (Monday), Day= 2(Tuesday), etc.)
Now, I can use a very messy looking switch statement with nested if statements that says, depending on the value of Day, and the number of days in that month, print out this pre-made calendar, and I can just pre-make a calendar for every eventual combination of Day and number of days in that month. But I don't want to do that, and I can't figure out an easier way of doing it. Has anybody got any ideas of a tidier, more succinct way of doing it? Would it be something involving 2d arrays?
PS. I'm not allowed to use any date-based library classes available in Java.
well you can use this if you change your mind
public static void main(String args [])
{
// type MM yyyy
Scanner in = new Scanner(System.in);
System.out.print("Enter month and year: MM yyyy ");
int month = in.nextInt();
int year = in.nextInt();
in.close();
// checks valid month
try {
if (month < 1 || month > 12)
throw new Exception("Invalid index for month: " + month);
printCalendarMonthYear(month, year);}
catch (Exception e) {
System.err.println(e.getMessage());
}
}
private static void printCalendarMonthYear(int month, int year) {
Calendar cal = new GregorianCalendar();
cal.clear();
cal.set(year, month - 1, 1); // setting the calendar to the month and year provided as parameters
System.out.println("Calendar for "+ cal.getDisplayName(Calendar.MONTH, Calendar.LONG,
Locale.US) + " " + cal.get(Calendar.YEAR));//to print Calendar for month and year
int firstWeekdayOfMonth = cal.get(Calendar.DAY_OF_WEEK);//which weekday was the first in month
int numberOfMonthDays = cal.getActualMaximum(Calendar.DAY_OF_MONTH); //lengh of days in a month
printCalendar(numberOfMonthDays, firstWeekdayOfMonth);
}
private static void printCalendar(int numberOfMonthDays, int firstWeekdayOfMonth) {
int weekdayIndex = 0;
System.out.println("Su MO Tu We Th Fr Sa"); // The order of days depends on your calendar
for (int day = 1; day < firstWeekdayOfMonth; day++) {
System.out.print(" "); //this loop to print the first day in his correct place
weekdayIndex++;
}
for (int day = 1; day <= numberOfMonthDays; day++) {
if (day<10) // this is just for better visialising because unit number take less space of course than 2
System.out.print(day+" ");
else System.out.print(day);
weekdayIndex++;
if (weekdayIndex == 7) {
weekdayIndex = 0;
System.out.println();
} else {
System.out.print(" ");
}}}
I'm trying to create a simple calendar app. In general, I want to print the calendar in month view. I am able to find the day and position of the first day of the month. After that, I want to add a day to the calendar and print the next day until I have printed all the days of that month. However, when I add one to the calendar, I don't get 2 (first day is 1), I get 9. Could someone please let me know why it's doing that. Here's what I have so far:
import java.util.Calendar;
import java.util.GregorianCalendar;
enum MONTHS
{
January, February, March, April, May, June, July, August, September, October, November, December;
}
enum DAYS
{
Su, Mo, Tu, We, Th, Fr, Sa;
}
public class MyCalendarTester {
static GregorianCalendar cal = new GregorianCalendar(); // capture today
public static void main(String[] args) {
// TODO Auto-generated method stub
MONTHS[] arrayOfMonths = MONTHS.values();
DAYS[] arrayOfDays = DAYS.values();
System.out.println(" " + arrayOfMonths[cal.get(Calendar.MONTH) - 1] + " " + cal.get(Calendar.YEAR)); //prints the month and year
for(int i = 0; i < arrayOfDays.length; i++){
if(i == 0){
System.out.print(arrayOfDays[i]);
}
else{
System.out.print(" " + arrayOfDays[i]);
}
}//print days of week
System.out.println();
for(int i = 0; i < arrayOfDays.length; i++){
if(!arrayOfDays[i].equals(arrayOfDays[cal.get(Calendar.DAY_OF_WEEK) - 1])){
System.out.println(" ");
}
else{
System.out.print(" " + Calendar.getInstance().getActualMinimum(Calendar.DAY_OF_MONTH));
break;
}
}
cal.add(Calendar.DAY_OF_MONTH, 1);
System.out.println(" " + cal.get(Calendar.DATE));
System.out.println("I think we're done here!");
}
}
The GregorianCalendar() constructor without any arguments constructs an instance of the GregorianCalendar class for todays date. In your code you use this constructor:
static GregorianCalendar cal = new GregorianCalendar(); // capture today
The day of the month, at the time of posting in 8. 8+1=9
To create a GregorianCalendar with the day of the month initialized to 1 you need to use GregorianCalendar(int year,int month,int dayOfMonth). As stated in the javadocs, this constructor
Constructs a GregorianCalendar with the given date set in the default time zone with the default locale.
static GregorianCalendar cal = new GregorianCalendar(2015,5,1);
The calendar object you're adding one to is static GregorianCalendar cal = new GregorianCalendar(); - that's why it said 9 (it is March, 9th)
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
There is one problem String has ":"
String time = "21:45";
How does convert this string to two int:
int hour = 21;
int minute = 45;
Straight forward, non-validating way:
String[] parts = time.split(":");
int hour = Integer.parseInt(parts[0]);
int minute = Integer.parseInt(parts[1]);
You should consider using Calendar to parse such time strings:
String time = "21:45";
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
sdf.setLenient(false);
Calendar calendar = Calendar.getInstance();
calendar.setTime(sdf.parse(time));
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
System.out.println(hour);
System.out.println(minute);
21
45
You can handle the potential ParseException to deal with invalid inputs.
Here a truely validating solution:
String time = "21:45";
boolean valid = true;
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
sdf.setLenient(false); // important for validation
GregorianCalendar gcal = new GregorianCalendar();
try {
gcal.setTime(sdf.parse(time));
} catch (ParseException pe) {
valid = false;
}
if (valid) {
int hours = gcal.get(Calendar.HOUR_OF_DAY);
int minutes = gcal.get(Calendar.MINUTE);
System.out.println("Hours: " + hours);
System.out.println("Minutes: " + minutes);
} else {
System.out.println("Sorry, the input is not valid: " + time);
}
Try this:
String arr[]= time.split(":", 2);
int num1 = Integer.parseInt(arr[0]);
int num2 = Integer.parseInt(arr[1]);