Android how to get tomorrow's date - java

In my android application. I need to display tomorrow's date, for example today is 5th March so I need to display as 6 March. I know the code for getting today's date, month and year.
date calculating
GregorianCalendar gc = new GregorianCalendar();
yearat = gc.get(Calendar.YEAR);
yearstr = Integer.toString(yearat);
monthat = gc.get(Calendar.MONTH) + 1;
monthstr = Integer.toString(monthat);
dayat = gc.get(Calendar.DAY_OF_MONTH);
daystr = Integer.toString(dayat);
If I have the code
dayat = gc.get(Calendar.DAY_OF_MONTH) + 1;
will it display tomorrow's date. or just add one to today's date? For example, if today is January 31. With the above code, will it display like 1 or 32? If it displays 32, what change I need to make?

Get today's date as a Calendar.
Add 1 day to it.
Format for display purposes.
For example,
GregorianCalendar gc = new GregorianCalendar();
gc.add(Calendar.DATE, 1);
// now do something with the calendar

Use the following code to display tomorrow date
Calendar calendar = Calendar.getInstance();
Date today = calendar.getTime();
calendar.add(Calendar.DAY_OF_YEAR, 1);
Date tomorrow = calendar.getTime();
Use SimpleDateFormat to format the Date as a String:
DateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
String todayAsString = dateFormat.format(today);
String tomorrowAsString = dateFormat.format(tomorrow);
System.out.println(todayAsString);
System.out.println(tomorrowAsString);
Prints:
05-Mar-2014
06-Mar-2014

Calendar calendar = Calendar.getInstance();
Date today = calendar.getTime();
calendar.add(Calendar.DAY_OF_YEAR, 1);
Date tomorrow = calendar.getTime();

you have to add just 1 in your Calendar Day.
GregorianCalendar gc = new GregorianCalendar();
gc.add(Calendar.DATE, 1);

java.util.Date and java.util.Calendar are terrible to work with. I suggest you use JodaTime which has a much cleaner / nicer API. JodaTime is pretty standard these days.
http://www.joda.org/joda-time/#Why_Joda-Time
Note that JDK 8 will introduce a new date/time API heavily influenced by JodaTime.
http://java.dzone.com/articles/introducing-new-date-and-time
https://jcp.org/en/jsr/detail?id=310

Other options:
Calendar tomorrow = Calendar.getInstance();
tomorrow.roll(Calendar.DATE, true);
or
tomorrow.roll(Calendar.DATE, 1);
roll can also be used to go back in time by passing a negative number, so for example:
Calendar yesterday = Calendar.getInstance();
yesterday.roll(Calendar.DATE, -1);

the first answers pretty much covers the possibilities.
but here one another solution which you can use from org.apache.commons.lang.time:
Date lTomorrow = DateUtils.addDays(new Date(), 1);

The java.util.Date and .Calendar classes are notoriously troublesome. Avoid them. Instead use either Joda-Time library or the new java.time package in bundled with Java 8.
Some example code using the Joda-Time 2.3 library.
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );
DateTime now = new DateTime( timeZone );
DateTime tomorrow = now.plusDays( 1 );
String output = DateTimeFormat.forPattern( "FF" ).withLocale(Locale.FRANCE).print( tomorrow );

Get todays date by using calendar and then add 1 day to it.

This is working to me well!!
Date currentDate = new Date();// get the current date
currentDate.setDate(currentDate.getDate() + 1);//add one day to the current date
dateView.setText(currentDate.toString().substring(0, 10));// put the string in specific format in my textView
good luck!!

much easier now
String today = LocalDateTime.now().format(DateTimeFormatter.ofPattern("MM-dd"));
String tomorrow = LocalDate.now().plusDays(1).format(DateTimeFormatter.ofPattern("MM-dd"));

Try like this..
dayat = gc.add(Calendar.DATE, 1);

tl;dr
java.time.LocalDate.now()
.plusDays( 1 )
java.time
All the other Answers are outmoded, using the troublesome old Date & Calendar classes or the Joda-Time project which is now in maintenance mode. The modern approach uses the java.time classes.
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone.
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment, so your results may vary. Better to specify your desired/expected time zone explicitly as an argument.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalDate today = LocalDate.now( z ) ;
From that LocalDate you can do math to get the following day.
LocalDate tomorrow = today.plusDays( 1 ) ;
Strings
To generate a String representing the LocalDate object’s value, call toString for text formatted per the ISO 8601 standard: YYYY-MM-DD.
To generate strings in other formats, search Stack Overflow for DateTimeFormatter.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

Best way for setting next day is
public void NextDate()
{
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
// set current date into textview
e_date.setText(new StringBuilder()
// Month is 0 based, just add 1
.append(mDay+1).append("-").append(mMonth + 1).append("-")
.append(mYear).append(" "));
}

Just call this method and send date from which you want next date
public String nextDate(Date dateClicked) {
//
String next_day;
calander_view.setCurrentDayTextColor(context.getResources().getColor(R.color.white_color));
//calander_view.setCurrentDayBackgroundColor(context.getResources().getColor(R.color.gray_color));
SimpleDateFormat dateFormatForDisplaying = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault());
String date_format = dateFormatForDisplaying.format(dateClicked);
SimpleDateFormat simpleDateformat = new SimpleDateFormat("E"); // the day of the week abbreviated
final Calendar calendar = Calendar.getInstance();
try {
Date date = dateFormatForDisplaying.parse(date_format);
calendar.setTime(date);
calendar.add(Calendar.DATE, 1);
String nex = dateFormatForDisplaying.format(calendar.getTime());
Date d1 = dateFormatForDisplaying.parse(nex);
String day_1 = simpleDateformat.format(d1);
next_day = nex + ", " + day_1;
} catch (ParseException e) {
e.printStackTrace();
}
return next_day;
}

String lastDate="5/28/2018";
Calendar calendar = Calendar.getInstance();
String[] sDate=lastDate.split("/");
calendar.set(Integer.parseInt(sDate[2]),Integer.parseInt(sDate[0]),Integer.parseInt(sDate[1]));
DateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
// String todayAsString = dateFormat.format(today);
for (int i=1;i<29;i++)
{
calendar.add(Calendar.DAY_OF_YEAR,1);
// td[i].setText(dateFormat.format(calendar.getTime()));
System.out.println(dateFormat.format(calendar.getTime()));
}

Related

Retrieving the time between two dates and checking if a month had passed [duplicate]

In Java how can I add one month to the current date?
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, 1);
Java 8
LocalDate futureDate = LocalDate.now().plusMonths(1);
You can make use of apache's commons lang DateUtils helper utility class.
Date newDate = DateUtils.addMonths(new Date(), 1);
You can download commons lang jar at http://commons.apache.org/proper/commons-lang/
tl;dr
LocalDate::plusMonths
Example:
LocalDate.now( )
.plusMonths( 1 );
Better to specify time zone.
LocalDate.now( ZoneId.of( "America/Montreal" )
.plusMonths( 1 );
java.time
The java.time framework is built into Java 8 and later. These classes supplant the old troublesome date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat. The Joda-Time team also advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.
Date-only
If you want the date-only, use the LocalDate class.
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );
today.toString(): 2017-01-23
Add a month.
LocalDate oneMonthLater = today.plusMonths( 1 );
oneMonthLater.toString(): 2017-02-23
Date-time
Perhaps you want a time-of-day along with the date.
First get the current moment in UTC with a resolution of nanoseconds.
Instant instant = Instant.now();
Adding a month means determining dates. And determining dates means applying a time zone. For any given moment, the date varies around the world with a new day dawning earlier to the east. So adjust that Instant into a time zone.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );
Now add your month. Let java.time handle Leap month, and the fact that months vary in length.
ZonedDateTime zdtMonthLater = zdt.plusMonths( 1 );
You might want to adjust the time-of-day to the first moment of the day when making this kind of calculation. That first moment is not always 00:00:00.0 so let java.time determine the time-of-day.
ZonedDateTime zdtMonthLaterStartOfDay = zdtMonthLater.toLocalDate().atStartOfDay( zoneId );
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 brought some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android (26+) bundle implementations of the java.time classes.
For earlier Android (<26), the process of API desugaring brings a subset of the java.time functionality not originally built into Android.
If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. See How to use ThreeTenABP….
Joda-Time
Update: The Joda-Time project is now in maintenance mode. Its team advises migration to the java.time classes. I am leaving this section intact for posterity.
The Joda-Time library offers a method to add months in a smart way.
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );
DateTime now = DateTime.now( timeZone );
DateTime nextMonth = now.plusMonths( 1 );
You might want to focus on the day by adjust the time-of-day to the first moment of the day.
DateTime nextMonth = now.plusMonths( 1 ).withTimeAtStartOfDay();
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, 1);
java.util.Date dt = cal.getTime();
(adapted from Duggu)
public static Date addOneMonth(Date date)
{
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.MONTH, 1);
return cal.getTime();
}
you can use DateUtils class in org.apache.commons.lang3.time package
DateUtils.addMonths(new Date(),1);
Use calander and try this code.
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MONTH, 1);
calendar.set(Calendar.DATE, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
Date nextMonthFirstDay = calendar.getTime();
calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
Date nextMonthLastDay = calendar.getTime();
public Date addMonths(String dateAsString, int nbMonths) throws ParseException {
String format = "MM/dd/yyyy" ;
SimpleDateFormat sdf = new SimpleDateFormat(format) ;
Date dateAsObj = sdf.parse(dateAsString) ;
Calendar cal = Calendar.getInstance();
cal.setTime(dateAsObj);
cal.add(Calendar.MONTH, nbMonths);
Date dateAsObjAfterAMonth = cal.getTime() ;
System.out.println(sdf.format(dateAsObjAfterAMonth));
return dateAsObjAfterAMonth ;
}`
If you need a one-liner (i.e. for Jasper Reports formula) and don't mind if the adjustment is not exactly one month (i.e "30 days" is enough):
new Date($F{invoicedate}.getTime() + 30L * 24L * 60L * 60L * 1000L)
This method returns the current date plus 1 month.
public Date addOneMonth() {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, 1);
return cal.getTime();
}`
public Date addMonth(Date inputDate, int monthToAddNumber){
Calendar calendar = Calendar.getInstance();
calendar.setTime(inputDate);
// Add 'monthToAddNumber' months to inputDate
calendar.add(Calendar.MONTH, monthToAddNumber);
return calendar.getTime();
}
then call method:
addMonth(new Date(), 1)
Use the plusMonths() method of the LocalDate class for Java 8 and Higher Versions.
// Add one month to the current local date
LocalDate localDate = LocalDate.now().plusMonths(1);
// Add one month to any local date object
LocalDate localDate = LocalDate.parse("2022-02-14").plusMonths(1); // 2022-03-14
Reference: https://www.javaexercise.com/java/java-add-months-to-date
You can use like this;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String d = "2000-01-30";
Date date= new Date(sdf.parse(d).getTime());
date.setMonth(date.getMonth() + 1);
In order to find the day after one month, it is necessary to look at what day of the month it is today.
So if the day is first day of month run following code
Calendar calendar = Calendar.getInstance();
Calendar calFebruary = Calendar.getInstance();
calFebruary.set(Calendar.MONTH, Calendar.FEBRUARY);
if (calendar.get(Calendar.DAY_OF_MONTH) == 1) {// if first day of month
calendar.add(Calendar.MONTH, 1);
calendar.set(Calendar.DATE, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
Date nextMonthFirstDay = calendar.getTime();
System.out.println(nextMonthFirstDay);
}
if the day is last day of month, run following codes.
else if ((calendar.getActualMaximum(Calendar.DAY_OF_MONTH) == calendar.get(Calendar.DAY_OF_MONTH))) {// if last day of month
calendar.add(Calendar.MONTH, 1);
calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
Date nextMonthLastDay = calendar.getTime();
System.out.println(nextMonthLastDay);
}
if the day is in february run following code
else if (calendar.get(Calendar.MONTH) == Calendar.JANUARY
&& calendar.get(Calendar.DAY_OF_MONTH) > calFebruary.getActualMaximum(Calendar.DAY_OF_MONTH)) {// control of february
calendar.add(Calendar.MONTH, 1);
calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
Date nextMonthLastDay = calendar.getTime();
System.out.println(nextMonthLastDay);
}
the following codes are used for other cases.
else { // any day
calendar.add(Calendar.DATE, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
Date theNextDate = calendar.getTime();
System.out.println(theNextDate);
}
Date dateAfterOneMonth = new DateTime(System.currentTimeMillis()).plusMonths(1).toDate();
Constants are in Portuguese because yes, but javadoc is understandable enough.
Just call
Calendar cal = Calendar.getInstance();
cal.setTime(yourDate);
DateSumUtil.sumOneMonth(cal);
and that's that. Related code:
package you.project.your_package_utils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
public class DateSumUtil {
private static Integer[] meses31 = { 2, 4, 7, 9 };
private static List<Integer> meses31List = Arrays.asList(meses31);
private static SimpleDateFormat s = new SimpleDateFormat("dd/MM/yyyy");
private static final int MES = Calendar.MONTH;
private static final int ANO = Calendar.YEAR;
private static final int DIA = Calendar.DAY_OF_MONTH;
/**
* Receives a date and adds one month. <br />
*
* #param c date to receive an added month, as {#code java.util.Calendar}
* #param dia day of month of the original month
*/
public static void addOneMonth(Calendar c, int dia) throws ParseException {
if (cal.get(MES) == 0) { if (dia < 29) cal.add(MES, 1);
else { if (cal.get(ANO) % 4 == 0) { if (dia < 30) cal.add(MES, 1);
else cal.setTime(s.parse("29/02/" + cal.get(ANO)));
} else { if (dia < 29) cal.add(MES, 1);
else cal.setTime(s.parse("28/02/" + cal.get(ANO)));
} } } else if (meses31List.contains(cal.get(MES))) {
if (dia < 31) { cal.add(Calendar.MONTH, 1);
cal.set(DIA, dia);
} else cal.setTime(s.parse("30/" + (cal.get(MES) + 2) + "/" + cal.get(ANO)));
} else { cal.add(MES, 1);
cal.set(DIA, dia); }
}
public class StringSplit {
public static void main(String[] args) {
// TODO Auto-generated method stub
date(5, 3);
date(5, 4);
}
public static String date(int month, int week) {
LocalDate futureDate = LocalDate.now().plusMonths(month).plusWeeks(week);
String Fudate = futureDate.toString();
String[] arr = Fudate.split("-", 3);
String a1 = arr[0];
String a2 = arr[1];
String a3 = arr[2];
String date = a3 + "/" + a2 + "/" + a1;
System.out.println(date);
return date;
}
}
Output:
10/03/2020
17/03/2020

Android: how to get the current day of the week (Monday, etc...) in the user's language?

I want to know what the current day of the week is (Monday, Tuesday...) in the user's local language. For example, "Lundi" "Mardi" etc... if the user is French.
I have read this post, it but it only returns an int, not a string with the day in the user's language: What is the easiest way to get the current day of the week in Android?
More generally, how do you get all the days of the week and all the months of the year written in the user's language ?
I think that this is possible, as for example the Google agenda gives the days and months written in the user's local language.
Use SimpleDateFormat to format dates and times into a human-readable string, with respect to the users locale.
Small example to get the current day of the week (e.g. "Monday"):
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Date d = new Date();
String dayOfTheWeek = sdf.format(d);
Try this:
int dayOfWeek = date.get(Calendar.DAY_OF_WEEK);
String weekday = new DateFormatSymbols().getShortWeekdays()[dayOfWeek];
I know already answered but who looking for 'Fri' like this
for Fri -
SimpleDateFormat sdf = new SimpleDateFormat("EEE");
Date d = new Date();
String dayOfTheWeek = sdf.format(d);
and who wants full date string they can use 4E for Friday
For Friday-
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Date d = new Date();
String dayOfTheWeek = sdf.format(d);
Enjoy...
To make things shorter You can use this:
android.text.format.DateFormat.format("EEEE", date);
which will return day of the week as a String.
Hers's what I used to get the day names (0-6 means monday - sunday):
public static String getFullDayName(int day) {
Calendar c = Calendar.getInstance();
// date doesn't matter - it has to be a Monday
// I new that first August 2011 is one ;-)
c.set(2011, 7, 1, 0, 0, 0);
c.add(Calendar.DAY_OF_MONTH, day);
return String.format("%tA", c);
}
public static String getShortDayName(int day) {
Calendar c = Calendar.getInstance();
c.set(2011, 7, 1, 0, 0, 0);
c.add(Calendar.DAY_OF_MONTH, day);
return String.format("%ta", c);
}
Try this...
//global declaration
private TextView timeUpdate;
Calendar calendar;
.......
timeUpdate = (TextView) findViewById(R.id.timeUpdate); //initialize in onCreate()
.......
//in onStart()
calendar = Calendar.getInstance();
//date format is: "Date-Month-Year Hour:Minutes am/pm"
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy HH:mm a"); //Date and time
String currentDate = sdf.format(calendar.getTime());
//Day of Name in full form like,"Saturday", or if you need the first three characters you have to put "EEE" in the date format and your result will be "Sat".
SimpleDateFormat sdf_ = new SimpleDateFormat("EEEE");
Date date = new Date();
String dayName = sdf_.format(date);
timeUpdate.setText("" + dayName + " " + currentDate + "");
The result is...
tl;dr
String output =
LocalDate.now( ZoneId.of( "America/Montreal" ) )
.getDayOfWeek()
.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH ) ;
java.time
The java.time classes built into Java 8 and later and back-ported to Java 6 & 7 and to Android include the handy DayOfWeek enum.
The days are numbered according to the standard ISO 8601 definition, 1-7 for Monday-Sunday.
DayOfWeek dow = DayOfWeek.of( 1 );
This enum includes the getDisplayName method to generate a String of the localized translated name of the day.
The Locale object specifies a human language to be used in translation, and specifies cultural norms to decide issues such as capitalization and punctuation.
String output = DayOfWeek.MONDAY.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH ) ;
To get today’s date, use the LocalDate class. Note that a time zone is crucial as for any given moment the date varies around the globe.
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );
DayOfWeek dow = today.getDayOfWeek();
String output = dow.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH ) ;
Keep in mind that the locale has nothing to do with the time zone.two separate distinct orthogonal issues. You might want a French presentation of a date-time zoned in India (Asia/Kolkata).
Joda-Time
UPDATE: The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
The Joda-Time library provides Locale-driven localization of date-time values.
DateTimeZone zone = DateTimeZone.forID( "America/Montreal" );
DateTime now = DateTime.now( zone );
Locale locale = Locale.CANADA_FRENCH;
DateTimeFormatter formatterUnJourQuébécois = DateTimeFormat.forPattern( "EEEE" ).withLocale( locale );
String output = formatterUnJourQuébécois.print( now );
System.out.println("output: " + output );
output: samedi
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8 and SE 9 and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
Sorry for late reply.But this would work properly.
daytext=(textview)findviewById(R.id.day);
Calender c=Calender.getInstance();
SimpleDateFormat sd=new SimpleDateFormat("EEEE");
String dayofweek=sd.format(c.getTime());
daytext.setText(dayofweek);
I just use this solution in Kotlin:
var date : String = DateFormat.format("EEEE dd-MMM-yyyy HH:mm a" , Date()) as String
If you are using ThreetenABP date library bt Jake Warthon you can do:
dayOfWeek.getDisplayName(TextStyle.FULL, Locale.getDefault()
on your dayOfWeek instance. More at:
https://github.com/JakeWharton/ThreeTenABP https://www.threeten.org/threetenbp/apidocs/org/threeten/bp/format/TextStyle.html
//selected date from calender
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy"); //Date and time
String currentDate = sdf.format(myCalendar.getTime());
//selcted_day name
SimpleDateFormat sdf_ = new SimpleDateFormat("EEEE");
String dayofweek=sdf_.format(myCalendar.getTime());
current_date.setText(currentDate);
lbl_current_date.setText(dayofweek);
Log.e("dayname", dayofweek);

How to get the current date/time in Java [duplicate]

This question already has answers here:
How to get the current date and time
(10 answers)
Closed 2 years ago.
What's the best way to get the current date/time in Java?
It depends on what form of date / time you want:
If you want the date / time as a single numeric value, then System.currentTimeMillis() gives you that, expressed as the number of milliseconds after the UNIX epoch (as a Java long). This value is a delta from a UTC time-point, and is independent of the local time-zone1.
If you want the date / time in a form that allows you to access the components (year, month, etc) numerically, you could use one of the following:
new Date() gives you a Date object initialized with the current date / time. The problem is that the Date API methods are mostly flawed ... and deprecated.
Calendar.getInstance() gives you a Calendar object initialized with the current date / time, using the default Locale and TimeZone. Other overloads allow you to use a specific Locale and/or TimeZone. Calendar works ... but the APIs are still cumbersome.
new org.joda.time.DateTime() gives you a Joda-time object initialized with the current date / time, using the default time zone and chronology. There are lots of other Joda alternatives ... too many to describe here. (But note that some people report that Joda time has performance issues.; e.g. https://stackoverflow.com/questions/6280829.)
in Java 8, calling java.time.LocalDateTime.now() and java.time.ZonedDateTime.now() will give you representations2 for the current date / time.
Prior to Java 8, most people who know about these things recommended Joda-time as having (by far) the best Java APIs for doing things involving time point and duration calculations.
With Java 8 and later, the standard java.time package is recommended. Joda time is now considered "obsolete", and the Joda maintainers are recommending that people migrate.3.
1 - System.currentTimeMillis() gives the "system" time. While it is normal practice for the system clock to be set to (nominal) UTC, there will be a difference (a delta) between the local UTC clock and true UTC. The size of the delta depends on how well (and how often) the system's clock is synced with UTC.
2 - Note that LocalDateTime doesn't include a time zone. As the javadoc says: "It cannot represent an instant on the time-line without additional information such as an offset or time-zone."
3 - Note: your Java 8 code won't break if you don't migrate, but the Joda codebase may eventually stop getting bug fixes and other patches. As of 2020-02, an official "end of life" for Joda has not been announced, and the Joda APIs have not been marked as Deprecated.
(Attention: only for use with Java versions <8. For Java 8+ check other replies.)
If you just need to output a time stamp in format YYYY.MM.DD-HH.MM.SS (very frequent case) then here's the way to do it:
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
If you want the current date as String, try this:
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date));
or
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime()));
http://www.mkyong.com/java/java-how-to-get-current-date-time-date-and-calender/
tl;dr
Instant.now() // Capture the current moment in UTC, with a resolution of nanoseconds. Returns a `Instant` object.
… or …
ZonedDateTime.now( // Capture the current moment as seen in…
ZoneId.of( "America/Montreal" ) // … the wall-clock time used by the people of a particular region (a time zone).
) // Returns a `ZonedDateTime` object.
java.time
A few of the Answers mention that java.time classes are the modern replacement for the troublesome old legacy date-time classes bundled with the earliest versions of Java. Below is a bit more information.
Time zone
The other Answers fail to explain how a time zone is crucial in determining the current date and time. For any given moment, the date and the time vary around the globe by zone. For example, a few minutes after midnight is a new day in Paris France while still being “yesterday” in Montréal Québec.
Instant
Much of your business logic and data storage/exchange should be done in UTC, as a best practice.
To get the current moment in UTC with a resolution in nanoseconds, use Instant class. Conventional computer hardware clocks are limited in their accuracy, so the current moment may be captured in milliseconds or microseconds rather than nanoseconds.
Instant instant = Instant.now();
ZonedDateTime
You can adjust that Instant into other time zones. Apply a ZoneId object to get a ZonedDateTime.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );
We can skip the Instant and get the current ZonedDateTime directly.
ZonedDateTime zdt = ZonedDateTime.now( z );
Always pass that optional time zone argument. If omitted, your JVM’s current default time zone is applied. The default can change at any moment, even during runtime. Do not subject your app to an externality out of your control. Always specify the desired/expected time zone.
ZonedDateTime do_Not_Do_This = ZonedDateTime.now(); // BAD - Never rely implicitly on the current default time zone.
You can later extract an Instant from the ZonedDateTime.
Instant instant = zdt.toInstant();
Always use an Instant or ZonedDateTime rather than a LocalDateTime when you want an actual moment on the timeline. The Local… types purposely have no concept of time zone so they represent only a rough idea of a possible moment. To get an actual moment you must assign a time zone to transform the Local… types into a ZonedDateTime and thereby make it meaningful.
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone.
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z ); // Always pass a time zone.
Strings
To generate a String representing the date-time value, simply call toString on the java.time classes for the standard ISO 8601 formats.
String output = myLocalDate.toString(); // 2016-09-23
… or …
String output = zdt.toString(); // 2016-09-23T12:34:56.789+03:00[America/Montreal]
The ZonedDateTime class extends the standard format by wisely appending the name of the time zone in square brackets.
For other formats, search Stack Overflow for many Questions and Answers on the DateTimeFormatter class.
Avoid LocalDateTime
Contrary to the comment on the Question by RamanSB, you should not use LocalDateTime class for the current date-time.
The LocalDateTime purposely lacks any time zone or offset-from-UTC information. So, this is not appropriate when you are tracking a specific moment on the timeline. Certainly not appropriate for capturing the current moment.
A LocalDateTime has only a date and a time-of-day such as "noon on 23rd of January 2020", but we have no idea if that is noon in Tokyo Japan or noon in Toledo Ohio US, two different moments many hours apart.
The “Local” wording is counter-intuitive. It means any locality rather than any one specific locality. For example Christmas this year starts at midnight on the 25th of December: 2017-12-25T00:00:00, to be represented as a LocalDateTime. But this means midnight at various points around the globe at different times. Midnight happens first in Kiribati, later in New Zealand, hours more later in India, and so on, with several more hours passing before Christmas begins in France when the kids in Canada are still awaiting that day. Each one of these Christmas-start points would be represented as a separate ZonedDateTime.
From outside your system
If you cannot trust your system clock, see Java: Get current Date and Time from Server not System clock and my Answer.
java.time.Clock
To harness an alternate supplier of the current moment, write a subclass of the abstract java.time.Clock class.
You can pass your Clock implementation as an argument to the various java.time methods. For example, Instant.now( clock ).
Instant instant = Instant.now( yourClockGoesHere ) ;
For testing purposes, note the alternate implementations of Clock available statically from Clock itself: fixed, offset, tick, and more.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
In Java 8 it is:
LocalDateTime.now()
and in case you need time zone info:
ZonedDateTime.now()
and in case you want to print fancy formatted string:
System.out.println(ZonedDateTime.now().format(DateTimeFormatter.RFC_1123_DATE_TIME))
Just create a Date object...
import java.util.Date;
Date date = new Date();
// 2015/09/27 15:07:53
System.out.println( new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(Calendar.getInstance().getTime()) );
// 15:07:53
System.out.println( new SimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime()) );
// 09/28/2015
System.out.println(new SimpleDateFormat("MM/dd/yyyy").format(Calendar.getInstance().getTime()));
// 20150928_161823
System.out.println( new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime()) );
// Mon Sep 28 16:24:28 CEST 2015
System.out.println( Calendar.getInstance().getTime() );
// Mon Sep 28 16:24:51 CEST 2015
System.out.println( new Date(System.currentTimeMillis()) );
// Mon Sep 28
System.out.println( new Date().toString().substring(0, 10) );
// 2015-09-28
System.out.println( new java.sql.Date(System.currentTimeMillis()) );
// 14:32:26
Date d = new Date();
System.out.println( (d.getTime() / 1000 / 60 / 60) % 24 + ":" + (d.getTime() / 1000 / 60) % 60 + ":" + (d.getTime() / 1000) % 60 );
// 2015-09-28 17:12:35.584
System.out.println( new Timestamp(System.currentTimeMillis()) );
// Java 8
// 2015-09-28T16:16:23.308+02:00[Europe/Belgrade]
System.out.println( ZonedDateTime.now() );
// Mon, 28 Sep 2015 16:16:23 +0200
System.out.println( ZonedDateTime.now().format(DateTimeFormatter.RFC_1123_DATE_TIME) );
// 2015-09-28
System.out.println( LocalDate.now(ZoneId.of("Europe/Paris")) ); // rest zones id in ZoneId class
// 16
System.out.println( LocalTime.now().getHour() );
// 2015-09-28T16:16:23.315
System.out.println( LocalDateTime.now() );
Use:
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
System.out.println(timeStamp );
(It's working.)
There are many different methods:
System.currentTimeMillis()
Date
Calendar
Create object of date and simply print it down.
Date d = new Date(System.currentTimeMillis());
System.out.print(d);
java.util.Date date = new java.util.Date();
It's automatically populated with the time it's instantiated.
Similar to above solutions. But I always find myself looking for this chunk of code:
Date date=Calendar.getInstance().getTime();
System.out.println(date);
For java.util.Date, just create a new Date()
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date)); //2016/11/16 12:08:43
For java.util.Calendar, uses Calendar.getInstance()
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal)); //2016/11/16 12:08:43
For java.time.LocalDateTime, uses LocalDateTime.now()
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
LocalDateTime now = LocalDateTime.now();
System.out.println(dtf.format(now)); //2016/11/16 12:08:43
For java.time.LocalDate, uses LocalDate.now()
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd");
LocalDate localDate = LocalDate.now();
System.out.println(dtf.format(localDate)); //2016/11/16
Reference: https://www.mkyong.com/java/java-how-to-get-current-date-time-date-and-calender/
1st Understand the java.util.Date class
1.1 How to obtain current Date
import java.util.Date;
class Demostration{
public static void main(String[]args){
Date date = new Date(); // date object
System.out.println(date); // Try to print the date object
}
}
1.2 How to use getTime() method
import java.util.Date;
public class Main {
public static void main(String[]args){
Date date = new Date();
long timeInMilliSeconds = date.getTime();
System.out.println(timeInMilliSeconds);
}
}
This will return the number of milliseconds since January 1, 1970, 00:00:00 GMT for time comparison purposes.
1.3 How to format time using SimpleDateFormat class
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
class Demostration{
public static void main(String[]args){
Date date=new Date();
DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
String formattedDate=dateFormat.format(date);
System.out.println(formattedDate);
}
}
Also try using different format patterns like "yyyy-MM-dd hh:mm:ss" and select desired pattern. http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
2nd Understand the java.util.Calendar class
2.1 Using Calendar Class to obtain current time stamp
import java.util.Calendar;
class Demostration{
public static void main(String[]args){
Calendar calendar=Calendar.getInstance();
System.out.println(calendar.getTime());
}
}
2.2 Try using setTime and other set methods for set calendar to different date.
Source: http://javau91.blogspot.com/
Have you looked at java.util.Date? It is exactly what you want.
Java 8 or above
LocalDateTime.now() and ZonedDateTime.now()
I find this to be the best way:
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime())); // 2014/08/06 16:00:22
Have a look at the Date class. There's also the newer Calendar class which is the preferred method of doing many date / time operations (a lot of the methods on Date have been deprecated.)
If you just want the current date, then either create a new Date object or call Calendar.getInstance();.
As mentioned the basic Date() can do what you need in terms of getting the current time. In my recent experience working heavily with Java dates there are a lot of oddities with the built in classes (as well as deprecation of many of the Date class methods). One oddity that stood out to me was that months are 0 index based which from a technical standpoint makes sense, but in real terms can be very confusing.
If you are only concerned with the current date that should suffice - however if you intend to do a lot of manipulating/calculations with dates it could be very beneficial to use a third party library (so many exist because many Java developers have been unsatisfied with the built in functionality).
I second Stephen C's recommendation as I have found Joda-time to be very useful in simplifying my work with dates, it is also very well documented and you can find many useful examples throughout the web. I even ended up writing a static wrapper class (as DateUtils) which I use to consolidate and simplify all of my common date manipulation.
Use:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy:MM:dd::HH:mm:ss");
System.out.println(sdf.format(System.currentTimeMillis()));
The print statement will print the time when it is called and not when the SimpleDateFormat was created. So it can be called repeatedly without creating any new objects.
System.out.println( new SimpleDateFormat("yyyy:MM:dd - hh:mm:ss a").format(Calendar.getInstance().getTime()) );
//2018:02:10 - 05:04:20 PM
date/time with AM/PM
New Data-Time API is introduced with the dawn of Java 8. This is due
to following issues that were caused in the old data-time API.
Difficult to handle time zone : need to write lot of code to deal with
time zones.
Not Thread Safe : java.util.Date is not thread safe.
So have a look around with Java 8
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.LocalDateTime;
import java.time.Month;
public class DataTimeChecker {
public static void main(String args[]) {
DataTimeChecker dateTimeChecker = new DataTimeChecker();
dateTimeChecker.DateTime();
}
public void DateTime() {
// Get the current date and time
LocalDateTime currentTime = LocalDateTime.now();
System.out.println("Current DateTime: " + currentTime);
LocalDate date1 = currentTime.toLocalDate();
System.out.println("Date : " + date1);
Month month = currentTime.getMonth();
int day = currentTime.getDayOfMonth();
int seconds = currentTime.getSecond();
System.out.println("Month : " + month);
System.out.println("Day : " + day);
System.out.println("Seconds : " + seconds);
LocalDateTime date2 = currentTime.withDayOfMonth(17).withYear(2018);
System.out.println("Date : " + date2);
//Prints 17 May 2018
LocalDate date3 = LocalDate.of(2018, Month.MAY, 17);
System.out.println("Date : " + date3);
//Prints 04 hour 45 minutes
LocalTime date4 = LocalTime.of(4, 45);
System.out.println("Date : " + date4);
// Convert to a String
LocalTime date5 = LocalTime.parse("20:15:30");
System.out.println("Date : " + date5);
}
}
Output of the coding above :
Current DateTime: 2018-05-17T04:40:34.603
Date : 2018-05-17
Month : MAY
Day : 17
Seconds : 34
Date : 2018-05-17T04:40:34.603
Date : 2018-05-17
Date : 04:45
Date : 20:15:30
I created this methods, it works for me...
public String GetDay() {
return String.valueOf(LocalDateTime.now().format(DateTimeFormatter.ofPattern("dd")));
}
public String GetNameOfTheDay() {
return String.valueOf(LocalDateTime.now().getDayOfWeek());
}
public String GetMonth() {
return String.valueOf(LocalDateTime.now().format(DateTimeFormatter.ofPattern("MM")));
}
public String GetNameOfTheMonth() {
return String.valueOf(LocalDateTime.now().getMonth());
}
public String GetYear() {
return String.valueOf(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy")));
}
public boolean isLeapYear(long year) {
return Year.isLeap(year);
}
public String GetDate() {
return GetDay() + "/" + GetMonth() + "/" + GetYear();
}
public String Get12HHour() {
return String.valueOf(LocalDateTime.now().format(DateTimeFormatter.ofPattern("hh")));
}
public String Get24HHour() {
return String.valueOf(LocalDateTime.now().getHour());
}
public String GetMinutes() {
return String.valueOf(LocalDateTime.now().format(DateTimeFormatter.ofPattern("mm")));
}
public String GetSeconds() {
return String.valueOf(LocalDateTime.now().format(DateTimeFormatter.ofPattern("ss")));
}
public String Get24HTime() {
return Get24HHour() + ":" + GetMinutes();
}
public String Get24HFullTime() {
return Get24HHour() + ":" + GetMinutes() + ":" + GetSeconds();
}
public String Get12HTime() {
return Get12HHour() + ":" + GetMinutes();
}
public String Get12HFullTime() {
return Get12HHour() + ":" + GetMinutes() + ":" + GetSeconds();
}
import java.util.*;
import java.text.*;
public class DateDemo {
public static void main(String args[]) {
Date dNow = new Date( );
SimpleDateFormat ft =
new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz");
System.out.println("Current Date: " + ft.format(dNow));
}
}
you can use date for fet current data. so using SimpleDateFormat get format
just try this code:
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class CurrentTimeDateCalendar {
public static void getCurrentTimeUsingDate() {
Date date = new Date();
String strDateFormat = "hh:mm:ss a";
DateFormat dateFormat = new SimpleDateFormat(strDateFormat);
String formattedDate= dateFormat.format(date);
System.out.println("Current time of the day using Date - 12 hour format: " + formattedDate);
}
public static void getCurrentTimeUsingCalendar() {
Calendar cal = Calendar.getInstance();
Date date=cal.getTime();
DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
String formattedDate=dateFormat.format(date);
System.out.println("Current time of the day using Calendar - 24 hour format: "+ formattedDate);
}
}
which the sample output is:
Current time of the day using Date - 12 hour format: 11:13:01 PM
Current time of the day using Calendar - 24 hour format: 23:13:01
more information on:
Getting Current Date Time in Java
Current Date using java 8:
First, let's use java.time.LocalDate to get the current system date:
LocalDate localDate = LocalDate.now();
To get the date in any other timezone we can use LocalDate.now(ZoneId):
LocalDate localDate = LocalDate.now(ZoneId.of("GMT+02:30"));
We can also use java.time.LocalDateTime to get an instance of LocalDate:
LocalDateTime localDateTime = LocalDateTime.now();
LocalDate localDate = localDateTime.toLocalDate();
You can use Date object and format by yourself. It is hard to format and need more codes, as a example,
Date dateInstance = new Date();
int year = dateInstance.getYear()+1900;//Returns:the year represented by this date, minus 1900.
int date = dateInstance.getDate();
int month = dateInstance.getMonth();
int day = dateInstance.getDay();
int hours = dateInstance.getHours();
int min = dateInstance.getMinutes();
int sec = dateInstance.getSeconds();
String dayOfWeek = "";
switch(day){
case 0:
dayOfWeek = "Sunday";
break;
case 1:
dayOfWeek = "Monday";
break;
case 2:
dayOfWeek = "Tuesday";
break;
case 3:
dayOfWeek = "Wednesday";
break;
case 4:
dayOfWeek = "Thursday";
break;
case 5:
dayOfWeek = "Friday";
break;
case 6:
dayOfWeek = "Saturday";
break;
}
System.out.println("Date: " + year +"-"+ month + "-" + date + " "+ dayOfWeek);
System.out.println("Time: " + hours +":"+ min + ":" + sec);
output:
Date: 2017-6-23 Sunday
Time: 14:6:20
As you can see this is the worst way you can do it and according to oracle documentation it is deprecated.
Oracle doc:
The class Date represents a specific instant in time, with millisecond
precision.
Prior to JDK 1.1, the class Date had two additional functions. It
allowed the interpretation of dates as year, month, day, hour, minute,
and second values. It also allowed the formatting and parsing of date
strings. Unfortunately, the API for these functions was not amenable
to internationalization. As of JDK 1.1, the Calendar class should be
used to convert between dates and time fields and the DateFormat class
should be used to format and parse date strings. The corresponding
methods in Date are deprecated.
So alternatively, you can use Calendar class,
Calendar.YEAR;
//and lot more
To get current time, you can use:
Calendar rightNow = Calendar.getInstance();
Doc:
Like other locale-sensitive classes, Calendar provides a class method,
getInstance, for getting a generally useful object of this type.
Calendar's getInstance method returns a Calendar object whose calendar
fields have been initialized with the current date and time
Below code for to get only date
Date rightNow = Calendar.getInstance().getTime();
System.out.println(rightNow);
Also, Calendar class have Subclasses. GregorianCalendar is a one of them and concrete subclass of Calendar and provides the standard calendar system used by most of the world.
Example using GregorianCalendar:
Calendar cal = new GregorianCalendar();
int hours = cal.get(Calendar.HOUR);
int minute = cal.get(Calendar.MINUTE);
int second = cal.get(Calendar.SECOND);
int ap = cal.get(Calendar.AM_PM);
String amVSpm;
if(ap == 0){
amVSpm = "AM";
}else{
amVSpm = "PM";
}
String timer = hours + "-" + minute + "-" + second + " " +amVSpm;
System.out.println(timer);
You can use SimpleDateFormat, simple and quick way to format date:
String pattern = "yyyy-MM-dd";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
String date = simpleDateFormat.format(new Date());
System.out.println(date);
Read this Jakob Jenkov tutorial: Java SimpleDateFormat.
As others mentioned, when we need to do manipulation from dates, we didn't had simple and best way or we couldn't satisfied built in classes, APIs.
As a example, When we need to get different between two dates, when we need to compare two dates(there is in-built method also for this) and many more. We had to use third party libraries. One of the good and popular one is Joda Time.
Also read:
How to get properly current date and time in Joda-Time?
JodaTime - how to get current time in UTC
Examples for JodaTime.
Download Joda
.
The happiest thing is now(in java 8), no one need to download and use libraries for any reasons. A simple example to get current date & time in Java 8,
LocalTime localTime = LocalTime.now();
System.out.println(localTime);
//with time zone
LocalTime localTimeWtZone = LocalTime.now(ZoneId.of("GMT+02:30"));
System.out.println(localTimeWtZone);
One of the good blog post to read about Java 8 date.
And keep remeber to find out more about Java date and time because there is lot more ways and/or useful ways that you can get/use.
Oracle tutorials for date & time.
Oracle tutorials for formatter.
Lesson: Standard Calendar.
EDIT:
According to #BasilBourque comment, the troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleTextFormat are now legacy, supplanted by the java.time classes.
I'll go ahead and throw this answer in because it is all I needed when I had the same question:
Date currentDate = new Date(System.currentTimeMillis());
currentDate is now your current date in a Java Date object.

convert date from "2009-12 Dec" format to "31-DEC-2009"

'2009-12 Dec' should be converted to '31-DEC-2009'
'2010-09 Sep' should be converted to '30-SEP-2010'
'2010-02 Feb' should be converted to '28-FEB-2010'
'2008-02 Feb' should be converted to '29-FEB-2008'
The values 2009-12 Dec, 2008-02 Feb will be displayed to the User in a drop down. The User have no option to select the DAY.
The user selected value should be passed to the Database. But the database expects the date in the format DD-MMM-YYYY. The query has '<= USER_DATE' condition. So, the last day of the month should be automatically selected and passed to the database.
Pl help me in writing the function that does the above job.
static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM MMM");
public static String convertMapedToSqlFormat(final String maped) {
String convertedMaped = null;
//....
return convertedMaped;
}
#Test
public void testConvertMapedToSqlFormat() {
String[] mapedValues = { "2009-12 Dec", "2009-11 Nov", "2009-10 Oct",
"2009-09 Sep", "2009-08 Aug", "2009-07 Jul", "2009-06 Jun",
"2009-05 May", "2009-04 Apr", "2009-03 Mar", "2009-02 Feb",
"2009-01 Jan", "2008-12 Dec", "2008-11 Nov", "2008-10 Oct" };
for (String maped : mapedValues) {
System.out.println(convertMapedToSqlFormat(maped));
}
}
Convert it to Calendar and use Calendar#getActualMaximum() to obtain last day of month and set the day with it.
Kickoff example:
String oldString = "2009-12 Dec";
Calendar calendar = Calendar.getInstance();
calendar.setTime(new SimpleDateFormat("yyyy-MM").parse(oldString)); // Yes, month name is ignored but we don't need this.
calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));
String newString = new SimpleDateFormat("dd-MMM-yyyy").format(calendar.getTime()).toUpperCase();
System.out.println(newString); // 31-DEC-2009
Use your DateFormat (but fix it to yyyy-dd MMM) to parse the date
convert the Date to Calendar
Use Calendar.getActualMaximim()
use dd-MMM-yyyy to format the obtained date.
call .toUpperCase()
So:
static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM MMM");
static SimpleDateFormat dbDateFormat = new SimpleDateFormat("yyyy-MMM-dd");
public static String convertMapedToSqlFormat(final String maped) {
Date date = dateFormat.parse(mapped);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
return dbDateFormat.format(cal.getTime()).toUpperCase();
}
A few notes:
if possible use joda-time DateTime
avoid having strict date formats in the database.
Get the year and month from the YYYY-MM part of the string.
Use JODA to create a point in time corresponding to the first day of that month. Move one month forward, and one day backward. Flatten the time to the string representation you need.
Hi you have to parse your date,
like so
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
Date du = new Date();
du = df.parse(sDate);
df = new SimpleDateFormat("yyyy-MM-dd");
sDate = df.format(du);
Hope this helps.
Let me know if it does.
PK
java.time
Much easier now with the modern java.time classes that supplant the troublesome old date-time classes seen here in the Question and other Answers.
The java.time framework is built into Java 8 and later. These classes supplant the old troublesome date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.
Now in maintenance mode, the Joda-Time project also advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time.
YearMonth
The YearMonth class provides just what you want.
YearMonth start = YearMonth.of( 2008 , Month.OCTOBER );
YearMonth stop = YearMonth.of( 2009 , Month.DECEMBER );
List<YearMonth> yms = new ArrayList<>();
YearMonth ym = start ;
while( ! ym.isAfter( stop ) ) {
yms.add( ym );
// Set up the next loop.
ym = ym.plusMonths( 1 );
}
To present, use a DateTimeFormatter to generate a String representation of the YearMonth value.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM MMM" );
f = f.withLocale( Locale.CANADA_FRENCH ); // Or Locale.US etc.
String output = ym.format( f );
To get the last day of the month, interrogate the YearMonth object.
LocalDate endOfMonth = ym.atEndOfMonth();
To present, use a DateTimeFormatter. Either let instantiate a formatter that automatically localizes appropriate to a specified Locale, or specify your own formatting pattern. Shown many times in many other Questions and Answers on Stack Overflow.

extract day from Date

I receive a timestamp from a SOAP service in milliseconds. So I do this:
Date date = new Date( mar.getEventDate() );
How can I extract the day of the month from date, since methods such as Date::getDay() are deprecated?
I am using a small hack, but I do not think this is the proper way to obtain day-of-month.
SimpleDateFormat sdf = new SimpleDateFormat( "dd" );
int day = Integer.parseInt( sdf.format( date ) );
Use Calendar for this:
Calendar cal = Calendar.getInstance();
cal.setTime(mar.getEventDate());
int day = cal.get(Calendar.DAY_OF_MONTH);
Update: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. See Tutorial by Oracle.
See the correct Answer by Ortomala Lokni, using the modern java.time classes. I am leaving this outmoded Answer intact as history.
The Answer by Lokni is correct.
Here is the same idea but using Joda-Time 2.8.
long millisSinceEpoch = mar.getEventDate() ;
DateTimeZone zone = DateTimeZone.forID( "America/Montreal" ) ; // Or DateTimeZone.UTC
LocalDate localDate = new LocalDate( millisSinceEpoch , zone ) ;
int dayOfMonth = localDate.getDayOfMonth() ;
Given the Date constructor used in the question
Date date = new Date(mar.getEventDate());
The method mar.getEventDate() returns a long that represent the specified number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT.
Java 8 and later
In Java 8, you can extract the day of the month from this value, assuming UTC, with
LocalDateTime.ofEpochSecond(mar.getEventDate(),0,ZoneOffset.UTC).getDayOfMonth();
Note also that the answer given by cletus assume that mar.getEventDate() returns a Date object which is not the case in the question.

Categories

Resources