I have tried this code. I got the output but not the right one...
//Iam getting my answer after the following changes below...
package patternsamp;
import java.io.*;
import java.util.*;
public class Mydate
{
static void test()
{
Date da = new Date(5,9,2014,07,00,00);
System.out.println(da.toGMTString());
}
public static void main(String[] args)
{
Mydate.test();
}
}
//I made the changes like this.....
Date da = new Date(114,8,5,12,30,0);
OUTPUT: 5 Sep 2014 07:00:00 GMT
This gives me right output... Thanks for your support friends.....
To get the sep 5 as output, shuold be given as 5-9,
Try using simpledateformat:
SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
String dateInString = "5-9-2014 07:00:00";
Date date = sdf.parse(dateInString);
System.out.println(date);
Quoting from Java Doc
Date(int year, int month, int date, int hrs, int min, int sec)
`Deprecated. As of JDK version 1.1, replaced by Calendar.set(year + 1900, month, date, hrs, min, sec) or GregorianCalendar(year + 1900, month, date, hrs, min, sec).`
Avoid using Date constructor (to set dates) at all, incase you insist maintain correct order of parameters, your code should look like this:-
package patternsamp;
import java.io.*;
import java.util.*;
public class Mydate
{
static void test()
{
Date da = new Date(114,9,5,07,00,00);
System.out.println(da.toGMTString());
}
public static void main(String[] args)
{
Mydate.test();
}
Note that I am using 114 in the year (and not 2014), since according to doc
A year y is represented by the integer y - 1900.
Hence to represent 2014 , you have to 2014-1900, which is 114.
if your project imported commons-lang.jar
you can get the Date object from String like this:
DateUtils.parseDate("2014-08-20",new String[]{"yyyy-MM-dd"})
Joda-Time
So much easier and sensible to use the Joda-Time library rather than the notoriously troublesome bundled java.util.Date and .Calendar classes. To specify a year, you specify a year (2014 rather than 114). To specify a month, you specify a month (9 means September rather than 8).
DateTime dateTime = new DateTime( 2014, 9, 5, 7, 0, 0, DateTimeZone.UTC );
If you must have a java.util.Date object, convert.
java.util.Date date = dateTime.toDate();
Related
I am new to using DateTimeFormatter package, and same thing we are able to get using SimpleDateFormat.
Date date = new SimpleDateFormat("MMMM").parse(month);//"DECEMBER"
Date date = new SimpleDateFormat("yyyy").parse(year);//"2020"
How to achive this using DateTimeFormatter?
DateTimeFormatter not supporting with util.Date class, here you need to use LocalDate class. You can't parse only with month or year, you should pass 3 values of month, day and year to get Date.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy MM dd");
LocalDate parsedDate = LocalDate.parse("2020 12 15", formatter);
System.out.print(parsedDate); //2020-12-15
String monthString = "December";
DateTimeFormatter monthFormatter
= DateTimeFormatter.ofPattern("MMMM", Locale.ENGLISH);
Month month = monthFormatter.parse(monthString, Month::from);
System.out.println(month);
Output:
DECEMBER
Year is somewhat simpler. We don’t need a formatter.
String yearString = "2020";
Year year = Year.parse(yearString);
System.out.println(year);
2020
The old Date class despite its name never represented a date. It was a point in time. Yet we commonly used it for a date, a time of day, a month, a year and still more purposes, sometimes also for the point in time that it was. One very confusing consequence was that the Date objects obtained from the code in your question would under rare circumstances incorrectly print as November instead of December and as 2019 instead of 2020. You should no longer use the Date class. It was always poorly designed and is long outdated.
On the other hand java.time, the modern Java date and time API to which DateTimeFormatter belongs, defines a class for each such concept: LocalDate for a date, Month for a month of year, Year for a year, etc. It makes our code clearer about what we are dealing with, which is good. It also requires us to learn about the different classes and think about which one to use each time.
If your month string was in all uppercase, we need to tell the formatter to parse without regard to case:
String monthString = "DECEMBER";
DateTimeFormatter monthFormatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern("MMMM")
.toFormatter(Locale.ENGLISH);
Month month = monthFormatter.parse(monthString, Month::from);
Also when your month name is in English remember to specify an English-speaking locale.
check this link https://www.baeldung.com/java-datetimeformatter.
you can use custom format as
String europeanDatePattern = "dd.MM.yyyy";
DateTimeFormatter europeanDateFormatter = DateTimeFormatter.ofPattern(europeanDatePattern);
System.out.println(europeanDateFormatter.format(LocalDate.of(2016, 7, 31)))
The date-time API of java.util and their formatting API, SimpleDateFormat are outdated and error-prone. Let's see them in action:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) throws ParseException {
Date date1 = new SimpleDateFormat("MMMM").parse("DECEMBER");
System.out.println(date1);
Date date2 = new SimpleDateFormat("yyyy").parse("2020");
System.out.println(date2);
}
}
Output:
Tue Dec 01 00:00:00 GMT 1970
Wed Jan 01 00:00:00 GMT 2020
I do not need to explain what defaults they are taking. Instead of taking such unexpected defaults, they should have raised an alarm (throw some exception) which would have become helpful to a programmer to react to.
Because of such surprises, it is recommended to stop using them completely and switch to the modern date-time API.
Note: For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7.
If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
Using the modern date-time API:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
public class Main {
public static void main(String[] args) {
System.out.println(parse("DECEMBER", "MMMM"));
System.out.println(parse("2020", "uuuu"));
}
static LocalDate parse(String text, String pattern) {
try {
return LocalDate.parse(text, DateTimeFormatter.ofPattern(pattern));
} catch (DateTimeParseException e) {
System.out.println(e.getMessage());
// Return some default value
return LocalDate.MIN;
}
}
}
Output:
Text 'DECEMBER' could not be parsed at index 0
-999999999-01-01
Text '2020' could not be parsed: Unable to obtain LocalDate from TemporalAccessor: {Year=2020},ISO of type java.time.format.Parsed
-999999999-01-01
So, now you (the programmer) get to know that you have to do something (e.g. use your own defaults) to parse the strings.
Demo:
import java.time.LocalDate;
import java.time.Month;
import java.time.Year;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.DateTimeParseException;
import java.time.temporal.ChronoField;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
LocalDate date = parse("DECEMBER", "MMMM");
Month month = parse("DECEMBER", "MMMM").getMonth();
System.out.println(date);
System.out.println(month);
date = parse("2020", "uuuu");
System.out.println(date);
int year = date.getYear();
System.out.println(year);
Year objYear = Year.of(year);
System.out.println(objYear);
}
static LocalDate parse(String text, String pattern) {
LocalDate today = LocalDate.now();
// Formatter using today's day, month and year as defaults
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern(pattern)
.parseDefaulting(ChronoField.DAY_OF_MONTH, today.getDayOfMonth())
.parseDefaulting(ChronoField.MONTH_OF_YEAR, today.getMonthValue())
.parseDefaulting(ChronoField.YEAR, today.getYear())
.toFormatter(Locale.ENGLISH);
try {
return LocalDate.parse(text, formatter);
} catch (DateTimeParseException e) {
System.out.println(e.getMessage());
// Return some default value
return LocalDate.MIN;
}
}
}
Output:
2020-12-15
DECEMBER
2020-12-15
2020
2020
If you do not want to create a date or date-time object, rather, if all you want to do is to parse your string into Month and Year, you can do it simply the following way:
import java.time.Month;
import java.time.Year;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.TextStyle;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
Month month = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern("MMMM")
.toFormatter(Locale.ENGLISH)
.parse("DECEMBER", Month::from);
System.out.println(month + " | " + month.getDisplayName(TextStyle.SHORT, Locale.ENGLISH) + " | "
+ month.getDisplayName(TextStyle.FULL, Locale.ENGLISH));
Year year = DateTimeFormatter.ofPattern("uuuu").parse("2020", Year::from);
System.out.println(year);
}
}
Output:
DECEMBER | Dec | December
2020
Learn more about the modern date-time API at Trail: Date Time.
This question already has answers here:
Printing out datetime in a specific format in Java?
(4 answers)
Closed 3 years ago.
I want to remove the time from dateAndTime, and also want to have all of them in numeric form like this: 10-10-2019
output: Wed Nov 10 16:39:58 AST 2010
public static void main(String args[]){
//Java calendar in default timezone and default locale
int day =10;
int month =10;
int year =10;
Calendar m = Calendar.getInstance();
m.set(year, month, day);
m.add(day, 10);
System.out.println(" Date :" + m.getTime());
Use SimpleDateFormat. There's a lot of example you can use.
you can use SimpleDateFormat for early versions of java or DateTimeFormatter for java8+.
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
public class DateTests {
public static void main(String[] args) {
//java8+
//recommended
String formattedToday = DateTimeFormatter.ofPattern("MM-dd-YYYY").format(LocalDateTime.now());
System.out.println(formattedToday);
//early versions of java
Calendar today = Calendar.getInstance();
String formatted = new SimpleDateFormat("MM-dd-YYYY").format(today.getTime());
System.out.println(formatted);
}
}
output:
09-18-2019
09-18-2019
Also read Calendar date to yyyy-MM-dd format in java
I am developing an application where I want to add hours. But I don't know how to do to take into account change of day for example. If I have
9:45 pm + 3:30
it should give
1:15 am
Thanks for help
String time = "2:00 pm";
SimpleDateFormat df = new SimpleDateFormat("hh:mm a");
Date date = df.parse(time);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.HOUR, 3);
cal.add(Calendar.MINUTE, 30);
int h = cal.get(Calendar.HOUR_OF_DAY);
int m = cal.get(Calendar.MINUTE);
It will print 5:30 pm
EDIT: HOUR_OF_DAY provides a 24 h day
import java.util.Calendar;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.text.DateFormat;
class SumHours{
public static void main(String[] args){
DateFormat dateFormat = new SimpleDateFormat("h:mm a");
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY,21);
cal.set(Calendar.MINUTE,45);
Date d = cal.getTime();
System.out.println(dateFormat.format(d));
cal.add(Calendar.HOUR, 3);
cal.add(Calendar.MINUTE, 30);
d = cal.getTime();
System.out.println(dateFormat.format(d));
}
}
Output:
9:45 PM
1:15 AM
Since so many have wanted to contribute an answer to this duplicate question (as I regard it), I thought it was time someone contributed the modern answer.
I know you are on Android Java 7, and until Java 8 comes to Android the modern answer requires you to use an external library, the ThreeTenABP. However, not only are the newer Java date and time classes in that library so much nicer to work with, when it comes to time arithmetic this is where they have one of their particularly strong points. So think about it, try it out. It’s also the future since the classes come built-in with Java 8 and later.
DateTimeFormatter timeFormatter
= DateTimeFormatter.ofPattern("h:mm a", Locale.ENGLISH);
LocalTime startTime = LocalTime.of(21, 45);
Duration hoursToAdd = Duration.ofHours(3).plusMinutes(30);
LocalTime resultTime = startTime.plus(hoursToAdd);
System.out.println("" + startTime.format(timeFormatter) + " + " + hoursToAdd
+ " = " + resultTime.format(timeFormatter));
This prints:
9:45 PM + PT3H30M = 1:15 AM
I had wanted to give you lowercase pm and am and 3:30 as in your question. I admit we’re not quite there. In particular PT3H30M is peculiar if you haven’t learned ISO 8601 syntax. It means just 3 hours 30 minutes, easy enough when you know. Duration objects do not lend themselves well to formatting, it will help in Java 9, but as long as Java 8 hasn’t come to Android yet, let’s leave that. If you prefer lowercase pm, you may find the solution in this answer: displaying AM and PM in small letter after date formatting.
My code may not be that much shorter than the code in the other answers, but IMHO it is much easier to read.
Further links
ThreeTenABP
How to use ThreeTenABP in Android Project
Here is one of the decissions when you want to call this in anywhere:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class TimeClass {
static String timeStart24 = "21:45";
static String timeStart = "09:45 PM";
static String timeStep = "3:30";
public String TimeClass(String start, String step) throws ParseException {
// Take hours and minutes apart
String[] time = step.split(":");
// Create format of time
SimpleDateFormat df = new SimpleDateFormat("hh:mm a");
SimpleDateFormat df24 = new SimpleDateFormat("HH:mm");
// Input begining time
Date from = df.parse(start);
System.out.println(df.format(from));
System.out.println(df24.format(from) + " - 24 hours format");
// Create calendar instance
Calendar cal = Calendar.getInstance();
cal.setTime(from);
// Inner method add of Calendar
cal.add(Calendar.HOUR_OF_DAY, Integer.parseInt(time[0]));
cal.add(Calendar.MINUTE, Integer.parseInt(time[1]));
System.out.println(df.format(cal.getTime()));
// System.out.print(df24.format(cal.getTime()));
return df.format(cal.getTime());
}
public static void main(String[] args) throws ParseException {
TimeClass tc = new TimeClass();
tc.TimeClass(timeStart, timeStep);
}
}
OUTPUT:
09:45 PM
21:45 - 24 hours format
01:15 AM
I want to convert a date to a long value (that is the milliseconds)
I have a date like
2/11/2014
I want to calculate the date in long (manual)
What I've tried
(2014 - 1970 ) * 31449600000 + 11 * 2592000000 + 2 * 604800000
This equals 1413504000000.
But http://www.fileformat.info/tip/java/date2millis.htm tells me that 1413504000000 is
Date (America/New_York) Thursday, October 16, 2014 8:00:00 PM EDT
Date (GMT) Friday, October 17, 2014 12:00:00 AM GMT
Date (short/short format) 10/16/14 8:00 PM
Where I'm wrong?
Again, I want to do this manually, not using java code.
Do not re-invent the wheel. Time/date calculations are notoriously difficult, even standard java library does not get it right. Use JodaTime:
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
public class JodaTimeSample {
public static void main(String[] args) {
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy");
DateTime date = DateTime.parse("2/11/2014", formatter);
System.out.println("Date: " + date.toString());
System.out.println("Millis: " + date.getMillis());
}
}
If you are sure you could do it manually (huh, why? - looks like homework), open JodaTime source code and copy it. You won't invent it better. Or even better open, read and then try to write it in your editor.
why you do manually to convert date into long or long into date, write a simple java code which give you correct results after convention, I am using the simple programme and convert it as per my user
public class test {
public static void main(String[] args) {
Date dt=new Date(Long.valueOf(1390973400983L));
System.out.println(dt.toString());
Calendar cal=Calendar.getInstance();
cal.set(2014, Calendar.JANUARY, 29, 11, 00, 0);
System.out.println(cal.getTimeInMillis());
System.out.println();
}
}
for more information visit here
I want to display the arraylist like this:
[2013-11-01,2013-11-8,2013-11-15,2013-11-22,2013-11-29]
I am written the below code and i am passing the static values to that method:
import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
public class DateExample {
Calendar cal = Calendar.getInstance();
public static void main(String[] args) {
DateExample date=new DateExample();
date.getAllDaysInaMonth("2013",11,1);
}
public List<java.sql.Date> getAllDaysInaMonth(String year,int month,int day){
System.out.println(year+""+month+""+day);
cal.set(Calendar.DAY_OF_MONTH, 1);
int utilyear=cal.get(cal.YEAR);
String syear= Integer.toString(utilyear);
int utilmonth=cal.get(cal.MONTH);
int utilday=cal.get(cal.DAY_OF_MONTH);
List<java.sql.Date> arraylist=new ArrayList<java.sql.Date>();
while (month==cal.get(Calendar.MONTH)) {
System.out.println("while"+cal.getTime());
SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
String dateofutil=format.format(cal.getTime());
System.out.println("dateofutil"+dateofutil);
try {
java.sql.Date sqldate=new java.sql.Date(format.parse(dateofutil).getTime());
arraylist.add(sqldate);
} catch (ParseException e) {
e.printStackTrace();
}
cal.add(Calendar.DAY_OF_MONTH,1);
}
System.out.println("arraylist values"+arraylist);
return arraylist;
}
}
Here am passing static year,month,date to method as a parameters through that values am printing the dates like yyyy-MM-dd format when am passing 1 day then after 7 days date is printed
But the above code is not working properly give me correct code
There are two things to be changed here.
First,
while (month==cal.get(Calendar.MONTH)) {
needs to be changed to
while (month==cal.get(Calendar.MONTH)+1) {
because the according to docs
The first month of the year in the Gregorian and Julian calendars is JANUARY which is 0;
and the second thing is to make your ArrayList of type String and not Date, because Date does not have a format. You can only get a formatted String representation of it.
List<String> arraylist = new ArrayList<String>();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); // This can go out of the `while` loop though.
String dateofutil = format.format(cal.getTime());
arraylist.add(dateofutil);
You need to make the change below:
From
while (month==cal.get(Calendar.MONTH)) {
to
while ((month-1)==cal.get(Calendar.MONTH)) {
See more in Calendar.class ==> NOVEMBER , it is 10 rather 11. That's why previously you did not get the expected result. Change it and go ahead.
public final static int NOVEMBER = 10;
/**
* Value of the {#link #MONTH} field indicating the
* twelfth month of the year.
*/
public final static int DECEMBER = 11;
/**
* Value of the {#link #MONTH} field indicating the
* thirteenth month of the year. Although <code>GregorianCalendar</code>
* does not use this value, lunar calendars do.
*/
public final static int UNDECIMBER = 12;
The answer by R.J and the answer by MouseLearnJava are both correct.
This kind of date-time work is much easier using the Joda-Time library.
For one thing, Joda-Time counts from one unlike the zero-based silliness of java.util.Calendar. So the days of week are 1-7, months of year 1-12.
Here is some example code using Joda-Time 2.3 and Java 7.
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// import org.joda.time.format.*;
// Data passed into method.
int year = 2014;
int month = 2;
int day = 2;
java.util.List<DateTime> dateTimes = new ArrayList<DateTime>();
DateTime start = new DateTime( year, month, day, 0, 0, 0 );
DateTime dateTime = start;
while( dateTime.monthOfYear().equals( start.monthOfYear() ) ) {
dateTimes.add( dateTime ); // Collect each date-time object.
dateTime = dateTime.plusDays( 7 );
}
System.out.println( "The list: " + dateTimes );
for( DateTime item : dateTimes ){
System.out.println( ISODateTimeFormat.date().print( item ) );
}
When run…
The list: [2014-02-02T00:00:00.000-08:00, 2014-02-09T00:00:00.000-08:00, 2014-02-16T00:00:00.000-08:00, 2014-02-23T00:00:00.000-08:00]
2014-02-02
2014-02-09
2014-02-16
2014-02-23