I have a date and I need to know the day of the week, so I used a GregorianCalendar object but I get back some dates that are incorrect.
GregorianCalendar calendar = new GregorianCalendar(year, month, day);
int i = calendar.get(Calendar.DAY_OF_WEEK);
What am I doing wrong?
Thanks!
EDIT SOLUTION:
mont--;
GregorianCalendar calendar = new GregorianCalendar(year, month, day);
int i = calendar.get(Calendar.DAY_OF_WEEK);
if(i == 2){
dayOfTheWeek = "Mon";
} else if (i==3){
dayOfTheWeek = "Tue";
} else if (i==4){
dayOfTheWeek = "Wed";
} else if (i==5){
dayOfTheWeek = "Thu";
} else if (i==6){
dayOfTheWeek = "Fri";
} else if (i==7){
dayOfTheWeek = "Sat";
} else if (i==1){
dayOfTheWeek = "Sun";
}
TimeZone timezone = TimeZone.getDefault();
Calendar calendar = new GregorianCalendar(timezone);
calendar.set(year, month, day, hour, minute, second);
String monthName=calendar.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.getDefault());//Locale.US);
String dayName=calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault());//Locale.US);
Joda-Time
I use Joda-Time library for all date/time related operations. Joda takes into account you locale and gets results accordingly:
import org.joda.time.DateTime;
DateTime date = new DateTime(year, month, day, 0, 0, 0);
or
DateTime date = DateTime().now();
Day of week (int):
date.getDayOfWeek();
Day of week (short String) using toString() and DateTimeFormat options:
date.toString("EE");
tl;dr
myGregCal // `GregorianCalendar` is a legacy class, supplanted by the modern `java.time.ZonedDateTime` class.
.toZonedDateTime() // Convert to `ZonedDateTime`.
.getDayOfWeek(). // Extract a `DayOfWeek` enum object, one of seven pre-defined objects, one for each day of the week.
.getDisplayName( // Automatically localize, generating a `String` to represent the name of the day of the week.
TextStyle.SHORT , // Specify how long or abbreviated.
Locale.US // Locale determines the human language and cultural norms used in localization.
) // Returns a `String` object.
Mon
LocalDate.now( ZoneId.of( "Africa/Tunis" ) ) // Get current date for people in a certain region, without time-of-day and without time zone.
.getDayOfWeek() // Extract a `DayOfWeek` enum object.
.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH ) // Generate a string representing that day-of-week, localized using the human language and cultural norms of a particular locale.
lundi
java.time
Convert the troublesome old legacy java.util.GregorianCalendar object to a modern java.time object by calling new methods added to the old class.
ZonedDateTime zdt = myGregCal.toZonedDateTime();
Get the DayOfWeek enum object for that moment in that time zone.
DayOfWeek dow = zdt.getDayOfWeek();
dow.toString(): WEDNESDAY
Pass these DayOfWeek objects around your code rather than passing integers like 1-7 or strings like "MON". By using the enum objects you make your code more self-documenting, provide type-safety, and ensure a range of valid values.
For presentation to the user, ask the DayOfWeek object to translate the name of the day of the week to a human language defined in a Locale.
String output =
dow.getDisplayName(
TextStyle.FULL_STANDALONE ,
Locale.CANADA_FRENCH
)
;
mercredi
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.
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, 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 (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
Related
String DOB = new DateTime(Long.parseLong(dob) * 1000, DateTimeZone.UTC ).toString();
// Current
// YYYY-MM-DD
// DOB = "1994-05-10T00:00.000Z"
// Required
// DD-MM-YYYY
// DOB = "10-05-1994"
I want to remove the hh:mm:ss and format the date using Joda-Time DateTimeFormatter.
try this:
DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS zzz");
// pass your DOB String
DateTime jodatime = dtf.parseDateTime(DOB);
// Format for output
DateTimeFormatter dtfOut = DateTimeFormat.forPattern("dd-MM-yyyy");
// Print the date
System.out.println(dtfOut.print(jodatime));
tl;dr
Use java.time classes.
Instant.ofEpochSecond( 1_485_748_890L )
.atZone( ZoneId.of( "America/Montreal" ) )
.toLocalDate()
.format(
DateTimeFormatter.ofPattern ( "dd-MM-uuuu" )
.withLocale ( Locale.UK )
)
29-01-2017
Joda-Time
If you want a date-only value without a time-of-day, you should be using the org.joda.time.LocalDate class.
FYI, the Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. Much of java.time is back-ported to Java 6, Java 7, and Android (see below).
java.time
The LocalDate class represents a date-only value without time-of-day and without time zone.
LocalDate birthdate = LocalDate.of( 1994 , 5 , 10 );
If your input is a count of whole seconds since the epoch of first moment of 1970 in UTC (1970-01-01T00:00:00Z), convert to an Instant. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = Instant.ofEpochSecond( 1_485_748_890L );
To view this moment through the lens of a particular region’s wall-clock time, assign a time zone (ZoneId) to get a ZonedDateTime.
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.
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" );
ZonedDateTime zdt = instant.atZone( z );
The LocalDate class represents a date-only value without time-of-day and without time zone.
LocalDate ld = zdt.toLocalDate();
To generate a String representing the value of your object, call toString for a string in standard ISO 8601 format, YYYY-MM-DD.
ld.toString(): 2017-01-29
For other formats, use the DateTimeFormatter class. You can specify a formatting pattern, or let the class automatically localize.
DateTimeFormatter f = DateTimeFormatter.ofPattern ( "dd-MM-uuuu" ).withLocale ( Locale.UK );
String output = ld.format ( f );
instant.toString(): 2017-01-30T04:01:30Z
zdt.toString(): 2017-01-29T23:01:30-05:00[America/Montreal]
ld.toString(): 2017-01-29
output: 29-01-2017
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….
try this :
String textDate ="1994-05-10T00:00.000Z"; //Date to convert
DateTimeFormatter DATE_FORMAT = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ"); //Default format
SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()); //Needed format
DateTime dateTime = new DateTime(DATE_FORMAT.parseDateTime(textDate), DateTimeZone.forID(current.getID()));
Calendar cal=dateTime.toCalendar(Locale.getDefault());
String formatted = SIMPLE_DATE_FORMAT.format(cal.getTime()); //Final Required date
The GregorianCalendar constructor asks for the following:
GregorianCalendar(int year, int month, int dayOfMonth);
How can I extract the year, month, and day from an object I have created. Right now I'm using object.YEAR, object.MONTH, and object.DAY_OF_MONTH, but that does not seem to be giving me the right numbers.
Thanks.
Here I get a date based on which calendar date a user clicks. The user can then enter some information into that date which is stored in a HashMap keyed on GregorianCalendar.
cal.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
#Override
public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth) {
selectedDate = new GregorianCalendar(year, month, dayOfMonth);
Here I am trying to write the date from the GregorianCalendar year, month, and day parameters to a file to be used later.
private void writeToFile() {
try
{
PrintWriter writer = new PrintWriter(file, "UTF-8");
for (GregorianCalendar gregObject: recipes.keySet()) {
String[] value = recipes.get(gregObject);
int y = gregObject.YEAR;
int m = gregObject.MONTH;
int d = gregObject.DAY_OF_MONTH;
writer.printf("%d %d %d ", y, m, d);
Here is how I read from the file. When I read from the file I get the numbers 1,2,5 for year, month, and date which is wrong. The rest of the information read is correct.
try
{
Scanner getLine = new Scanner(file);
Scanner tokenizer;
while (getLine.hasNextLine()) {
String line = getLine.nextLine();
tokenizer = new Scanner(line);
System.out.println(line);
while (tokenizer.hasNextInt()) {
int y1 = tokenizer.nextInt();
int m1 = tokenizer.nextInt();
int d1 = tokenizer.nextInt();
Obviously I think I am writing the year, month, and day wrongly to the file, so I'm trying to figure out the correct way to extract the year, month, and day from a GregorianCalendar object.
Hope following helps: I am using 2015/06/10 as input. Please note month values are 0 (Jan) - 11 (Dec).
package demo;
import java.util.Calendar;
import java.util.GregorianCalendar;
/**
* Create on 4/3/16.
*/
public class TestCalendar {
public static void main(String [] args){
Calendar cal = new GregorianCalendar(2015,05,10); // Month values are 0(Jan) - 11 (Dec). So for June it is 05
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH); // 0 - 11
int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
// Following must output 2015/06/10
System.out.printf("Provided date is %4d/%02d/%02d", year, month+1, dayOfMonth);
}
}
tl;dr
You are working too hard.
You are using troublesome old date-time classes now supplanted by the modern java.time classes.
Example:
LocalDate.now().getYear() // Better to pass a specific time zone (`ZoneId`) as optional argument: LocalDate.now( ZoneId.of( "Africa/Tunis" ) ).getYear()
2018
java.time
Do not use a date-time class if you really only care about the date without the time.
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 ) ;
If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the JVM’s current default is applied implicitly. Better to be explicit, as the default may be changed at any moment during runtime by any code in any thread of any app within the JVM.
ZoneId z = ZoneId.systemDefault() ; // Get JVM’s current default time zone.
Or specify a date. You may set the month by a number, with sane numbering 1-12 for January-December.
LocalDate ld = LocalDate.of( 1986 , 2 , 23 ) ; // Years use sane direct numbering (1986 means year 1986). Months use sane numbering, 1-12 for January-December.
Or, better, use the Month enum objects pre-defined, one for each month of the year. Tip: Use these Month objects throughout your codebase rather than a mere integer number to make your code more self-documenting, ensure valid values, and provide type-safety.
LocalDate ld = LocalDate.of( 1986 , Month.FEBRUARY , 23 ) ;
year-month-day parts
Interrogate for the parts, as needed.
int ld.getYear() ;
int ld.getMonthValue() ;
int ld.getDayOfMonth() ;
Legacy code
If you must inter-operate with old code not yet converted to java.time, you may convert using new methods added to the old classes.
The equivalent of GregorianCalendar is ZonedDateTime.
ZonedDateTime zdt = myGregCal.toZonedDateTime() ; // Convert from legacy class to modern class.
Interrogate for the parts, as needed.
int zdt.getYear() ;
int zdt.getMonthValue() ;
int zdt.getDayOfMonth() ;
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….
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.
I want to get the current time on the device in the format: 2013-10-17 15:45:01 ?
The server sends me the date of an object in the format above as a string. Now i want to get the phones current time and then check if there is a difference of say more than 5 minutes?
So A: How can i get the devices current time in this fomat: 2013-10-17 15:45:01
B how can I work out the difference between the two.
You can use SimpleDateFormat to specify the pattern you want:
new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new java.util.Date())
However, if you just want to know whether the time difference is within a certain threshold, you should probably just compare long values. If your threshold is 5 minutes, then this is 5 * 60 * 1000 milliseconds so you can use the same SimpleDateFormat by calling it's parse method and check the long values.
Example:
new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse("2013-10-13 14:54:03").getTime()
Date currentDate = new Date(); will initialize a new date with the current time. In addition, convert the server provided time and take the difference.
String objectCreatedDateString = "2013-10-17 15:45:01";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date objectCreatedDate = null;
Date currentDate = new Date();
try
{objectCreatedDate = format.parse(objectCreatedDateString);}
catch (ParseException e)
{Log.e(TAG, e.getMessage());}
int timeDifferential;
if (objectCreatedDate != null)
timeDifferential = objectCreatedDate.getMinutes() - currentDate.getMinutes();
tl;dr
Duration.between( // Calculate time elapsed between two moments.
LocalDateTime // Represent a date with time-of-day but lacking the context of a time zone or offset-from-UTC.
.parse( "2013-10-17 15:45:01".replace( " " , "T" ) )
.atOffset( ZoneOffset.UTC ) // Returns an `OffsetDateTime` object.
.toInstant() , // Returns an `Instant` object.
Instant.now() // Capture the current moment as seen in UTC.
)
.toMinutes()
> 5
java.time
The other Answers are outdated, using terrible classes that were years ago supplanted by the modern java.time classes defined in JSR 310.
Parse your incoming string.
String input = "2013-10-17 15:45:01" ;
Modify the input to comply with ISO 8601. I suggest you educate the publisher of your data about the ISO 8601 standard.
String inoutModified = input.replace( " " , "T" ) ;
Parse as a LocalDateTime because this input lacks an indicator of the intended offset or time zone.
LocalDateTime ldt = LocalDateTime.parse( input ) ;
I assume that input was intended to represent a moment as seen in UTC, with an offset of zero hours minutes seconds. If so, educate the publisher of your data about appending a Z on the end to so indicate, per ISO 8601.
OffsetDateTime odt = ldt.atOffset( ZoneOffset.UTC ) ;
Extract an object of the simpler class, Instant. This class is always in UTC.
Instant then = odt.toInstant() ;
Get current moment as seen in UTC.
Instant now = Instant.now() ;
Calculate the difference.
Duration d = Duration.between( then , now ) ;
Get duration as total whole minutes.
long minutes = d.toMinutes() ;
Test.
if ( minutes > 5 ) { … }
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), a process known as 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….
Use SimpleDateFromat Class
DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
dateFormatter.format(date);
Also check this documentation
If you can ask the server to send you an RFC3339 compliant date/time string, then Here is a simple answer to both of your questions:
public String getClientTime() {
Time clientTime = new Time().setToNow();
return clientTime.format("%Y-%m-%d %H:%M:%S");
}
public int diffClientAndServerTime(String svrTimeStr) {
Time svrTime = new Time();
svrTime.parse3339(svrTimeStr);
Time clientTime = new Time();
clientTime.setToNow();
return svrTime.compare( svrTime, clientTime);
}
I want to convert my date (which is in String format), e.g. 13-09-2011, into Timestamp. I used below code but I got the 2011-09-13 00:00:00.0
as a result. But I want Timestamp like,1312828200000 format.
I cannot understand how to convert that.
My code:
String str_date="13-09-2011";
DateFormat formatter ;
Date date ;
formatter = new SimpleDateFormat("dd-MM-yyyy");
date = (Date)formatter.parse(str_date);
java.sql.Timestamp timeStampDate = new Timestamp(date.getTime());
System.out.println("Today is " +timeStampDate);
If you use getTime() of Date object you will get time in millisecond.
No need to use Timestamp to get your result.
String str_date="13-09-2011";
DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
Date date = (Date)formatter.parse(str_date);
System.out.println("Today is " +date.getTime());
The above code will print something like 1312828200000 you need and this is long value.
String str_date=month+"-"+day+"-"+yr;
DateFormat formatter = new SimpleDateFormat("MM-dd-yyyy");
Date date = (Date)formatter.parse(str_date);
long output=date.getTime()/1000L;
String str=Long.toString(output);
long timestamp = Long.parseLong(str) * 1000;
This line:
"Today is " +timeStampDate
calls TimeStamp.toString() method "which Formats a timestamp in JDBC timestamp escape format. yyyy-mm-dd hh:mm:ss.fffffffff, where ffffffffff indicates nanoseconds."
The TimeStamp you got internally has the value you want. If you want to get it than use:
System.out.println("Today is " + timeStampDate.getTime());
String str_date="13-09-2011";
DateFormat formatter ;
Date date ;
formatter = new SimpleDateFormat("dd-MM-yyyy");
date = (Date)formatter.parse(str_date);
java.sql.Timestamp timeStampDate = new Timestamp(date.getTime());
System.out.println("Today is " + timeStampDate.getTime());
Or if you don't need the Timestamp, you can directly use date.getTime(). It "Returns the Date as a millisecond value.":
String str_date="13-09-2011";
DateFormat formatter ;
Date date ;
formatter = new SimpleDateFormat("dd-MM-yyyy");
date = (Date)formatter.parse(str_date);
System.out.println("Today is " + date.getTime());
tl;dr
Use modern java.time classes.
LocalDate.parse(
"13-09-2011" ,
DateTimeFormatter.ofPattern( "dd-MM-uuuu" )
)
.atStartOfDay(
ZoneId.of( "Africa/Casablanca" ) // Or use `ZoneOffset.UTC` instead of a zone.
)
.toInstant()
.toEpochMilli()
See this code run live at IdeOne.com.
1315872000000
Details
Apparently you want to represent the first moment of a particular date as a count of milliseconds since the epoch reference of first moment of 1970 in UTC.
java.time
The modern approach uses the java.time classes that years ago supplanted the troublesome legacy classes such as Date, Calendar, and SimpleDateFormat.
First parse your input string as a LocalDate, for a date-only value without time-of-day and without time zone.
Tip: Rather then using such custom formats when exchanging date-time values as text, use standard ISO 8601 formats. The java.time classes use them by default when parsing/generating strings.
String input = "13-09-2011" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MM-uuuu" ) ;
LocalDate ld = LocalDate.parse( input , f ) ;
Determine the first moment of the day on that date. Doing so requires a time zone. 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 during runtime(!), 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 2-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" ) ;
Never assume the day starts at 00:00. In some zones on some dates, the day may start at another time such as 01:00. Let java.time determine first moment.
ZonedDateTime zdt = ld.startOfDay( z ) ; // Determine first moment of the day on this date in this zone. May not be 00:00.
Adjust to UTC from that zone by extracting a Instant.
Instant instant = zdt.toInstant() ;
Get a count of milliseconds since 1970-01-01T00:00Z. Beware of possible data loss, as an Instant carries a finer resolution of nanoseconds. Any microseconds or nanoseconds will be ignored.
long millisecondsSinceEpoch = instant.toEpochMilli() ;
You can go back the other direction, from a count-from-epoch to a Instant.
Instant instant = Instant.ofEpochMilli( millisecondsSinceEpoch) ;
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.
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….
Kotlin
val dateString = "17-09-2021"
val formatter = SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH)
val date = formatter.parse(dateString) as Date
Log.i("i","Today is " + date.time)
You'll get something that resembles 1616668471659
It may can help you
long time= System.currentTimeMillis();//timestamp in milliseconds of current time
String tp = Long.toString(time);//use timestamp as a string
I'm trying to return the name of the month as a String, for instance "May", "September", "November".
I tried:
int month = c.get(Calendar.MONTH);
However, this returns integers (5, 9, 11, respectively). How can I get the month name?
Use this :
Calendar cal=Calendar.getInstance();
SimpleDateFormat month_date = new SimpleDateFormat("MMMM");
String month_name = month_date.format(cal.getTime());
Month name will contain the full month name,,if you want short month name use
this
SimpleDateFormat month_date = new SimpleDateFormat("MMM");
String month_name = month_date.format(cal.getTime());
For getting month in string variable use the code below
For example the month of September:
M -> 9
MM -> 09
MMM -> Sep
MMMM -> September
String monthname=(String)android.text.format.DateFormat.format("MMMM", new Date())
Use getDisplayName.
For earlier API's use String.format(Locale.US,"%tB",c);
"MMMM" is definitely NOT the right solution (even if it works for many languages), use "LLLL" pattern with SimpleDateFormat
The support for 'L' as ICU-compatible extension for stand-alone month names was added to Android platform on Jun. 2010.
Even if in English there is no difference between the encoding by 'MMMM' and 'LLLL', your should think about other languages, too.
E.g. this is what you get, if you use Calendar.getDisplayName or the "MMMM" pattern for January with the Russian Locale:
января (which is correct for a complete date string: "10 января, 2014")
but in case of a stand-alone month name you would expect:
январь
The right solution is:
SimpleDateFormat dateFormat = new SimpleDateFormat( "LLLL", Locale.getDefault() );
dateFormat.format( date );
If you are interested in where all the translations come from - here is the reference to gregorian calendar translations (other calendars linked on top of the page).
As simple as this
mCalendar = Calendar.getInstance();
String month = mCalendar.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.getDefault());
Calendar.LONG is to get the full name of the month and Calendar.SHORT gives the name in short.
For eg: Calendar.LONG will return January
Calendar.SHORT will return Jan
I keep this answer which is useful for other cases, but #trutheality answer seems to be the most simple and direct way.
You can use DateFormatSymbols
DateFormatSymbols(Locale.FRENCH).getMonths()[month]; // FRENCH as an example
The only one way on Android to get properly formatted stanalone month name for such languages as ukrainian, russian, czech
private String getMonthName(Calendar calendar, boolean short) {
int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_NO_MONTH_DAY | DateUtils.FORMAT_NO_YEAR;
if (short) {
flags |= DateUtils.FORMAT_ABBREV_MONTH;
}
return DateUtils.formatDateTime(getContext(), calendar.getTimeInMillis(), flags);
}
Tested on API 15-25
Output for May is Май but not Мая
Russian.
Month
.MAY
.getDisplayName(
TextStyle.FULL_STANDALONE ,
new Locale( "ru" , "RU" )
)
май
English in the United States.
Month
.MAY
.getDisplayName(
TextStyle.FULL_STANDALONE ,
Locale.US
)
May
See this code run live at IdeOne.com.
ThreeTenABP and java.time
Here’s the modern answer. When this question was asked in 2011, Calendar and GregorianCalendar were commonly used for dates and times even though they were always poorly designed. That’s 8 years ago now, and those classes are long outdated. Assuming you are not yet on API level 26, my suggestion is to use the ThreeTenABP library, which contains an Android adapted backport of java.time, the modern Java date and time API. java.time is so much nicer to work with.
Depending on your exact needs and situation there are two options:
Use Month and its getDisplayName method.
Use a DateTimeFormatter.
Use Month
Locale desiredLanguage = Locale.ENGLISH;
Month m = Month.MAY;
String monthName = m.getDisplayName(TextStyle.FULL, desiredLanguage);
System.out.println(monthName);
Output from this snippet is:
May
In a few languages it will make a difference whether you use TextStyle.FULL or TextStyle.FULL_STANDALONE. You will have to see, maybe check with your users, which of the two fits into your context.
Use a DateTimeFormatter
If you’ve got a date with or without time of day, I find a DateTimeFormatter more practical. For example:
DateTimeFormatter monthFormatter = DateTimeFormatter.ofPattern("MMMM", desiredLanguage);
ZonedDateTime dateTime = ZonedDateTime.of(2019, 5, 31, 23, 49, 51, 0, ZoneId.of("America/Araguaina"));
String monthName = dateTime.format(monthFormatter);
I am showing the use of a ZonedDateTime, the closest replacement for the old Calendar class. The above code will work for a LocalDate, a LocalDateTime, MonthDay, OffsetDateTime and a YearMonth too.
What if you got a Calendar from a legacy API not yet upgraded to java.time? Convert to a ZonedDateTime and proceed as above:
Calendar c = getCalendarFromLegacyApi();
ZonedDateTime dateTime = DateTimeUtils.toZonedDateTime(c);
The rest is the same as before.
Question: Doesn’t java.time require Android API level 26?
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
I would recommend to use Calendar object and Locale, because month names are different for different languages:
// index can be in range 0 - 11
private String getMonthName(final int index, final Locale locale, final boolean shortName)
{
String format = "%tB";
if (shortName)
format = "%tb";
Calendar calendar = Calendar.getInstance(locale);
calendar.set(Calendar.MONTH, index);
calendar.set(Calendar.DAY_OF_MONTH, 1);
return String.format(locale, format, calendar);
}
Example for full month name:
System.out.println(getMonthName(0, Locale.US, false));
Result: January
Example for short month name:
System.out.println(getMonthName(0, Locale.US, true));
Result: Jan
A sample way to get the date and time in
this format "2018 Nov 01 16:18:22" use this
DateFormat dateFormat = new SimpleDateFormat("yyyy MMM dd HH:mm:ss");
Date date = new Date();
dateFormat.format(date);
Getting a standalone month name is surprisingly difficult to perform "right" in Java. (At least as of this writing. I'm currently using Java 8).
The problem is that in some languages, including Russian and Czech, the standalone version of the month name is different from the "formatting" version. Also, it appears that no single Java API will just give you the "best" string. The majority of answers posted here so far only offer the formatting version. Pasted below is a working solution for getting the standalone version of a single month name, or getting an array with all of them.
I hope this saves someone else some time!
/**
* getStandaloneMonthName, This returns a standalone month name for the specified month, in the
* specified locale. In some languages, including Russian and Czech, the standalone version of
* the month name is different from the version of the month name you would use as part of a
* full date. (Different from the formatting version).
*
* This tries to get the standalone version first. If no mapping is found for a standalone
* version (Presumably because the supplied language has no standalone version), then this will
* return the formatting version of the month name.
*/
private static String getStandaloneMonthName(Month month, Locale locale, boolean capitalize) {
// Attempt to get the standalone version of the month name.
String monthName = month.getDisplayName(TextStyle.FULL_STANDALONE, locale);
String monthNumber = "" + month.getValue();
// If no mapping was found, then get the formatting version of the month name.
if (monthName.equals(monthNumber)) {
DateFormatSymbols dateSymbols = DateFormatSymbols.getInstance(locale);
monthName = dateSymbols.getMonths()[month.getValue()];
}
// If needed, capitalize the month name.
if ((capitalize) && (monthName != null) && (monthName.length() > 0)) {
monthName = monthName.substring(0, 1).toUpperCase(locale) + monthName.substring(1);
}
return monthName;
}
/**
* getStandaloneMonthNames, This returns an array with the standalone version of the full month
* names.
*/
private static String[] getStandaloneMonthNames(Locale locale, boolean capitalize) {
Month[] monthEnums = Month.values();
ArrayList<String> monthNamesArrayList = new ArrayList<>();
for (Month monthEnum : monthEnums) {
monthNamesArrayList.add(getStandaloneMonthName(monthEnum, locale, capitalize));
}
// Convert the arraylist to a string array, and return the array.
String[] monthNames = monthNamesArrayList.toArray(new String[]{});
return monthNames;
}
It will provide current date and month:
fun getDateTime(): String?
{
val dateFormat: DateFormat = SimpleDateFormat("dd MMMM")
val date = Date()
return dateFormat.format(date)
}