java XMLGregorianCalendar shows different year on conversion [duplicate] - java

This question already has answers here:
Why does sdf.format(date) converts 2018-12-30 to 2019-12-30 in java? [duplicate]
(3 answers)
Java SimpleDateFormat returning wrong value in Date object
(1 answer)
Y returns 2012 while y returns 2011 in SimpleDateFormat
(5 answers)
Closed 3 years ago.
Simple test case below is giving results different than expected.
import javax.xml.datatype.XMLGregorianCalendar;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class Main {
public static void main(String[] args) {
XMLGregorianCalendar xmlDate = new XMLGregorianCalendarImpl();
xmlDate.setMonth(12);
xmlDate.setDay(31);
xmlDate.setYear(2019);
xmlDate.setHour(0);
xmlDate.setMinute(0);
xmlDate.setSecond(0);
Calendar calendar = xmlDate.toGregorianCalendar();
SimpleDateFormat formatter = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
Date dt = calendar.getTime();
String ds1 = dt.toString();
System.out.println("ds1 = " + ds1);
String dateString = formatter.format(calendar.getTime());
System.out.println("dateString = " + dateString );
}
}
I cannot figure out why the year component of dateString is showing as 2020 instead of 2019.
ds1 = Tue Dec 31 00:00:00 EST 2019
dateString = 2020-12-31 00:00:00

Please change your code to
import javax.xml.datatype.XMLGregorianCalendar;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class Main {
public static void main(String[] args) {
XMLGregorianCalendar xmlDate = new XMLGregorianCalendarImpl();
xmlDate.setMonth(12);
xmlDate.setDay(31);
xmlDate.setYear(2019);
xmlDate.setHour(0);
xmlDate.setMinute(0);
xmlDate.setSecond(0);
Calendar calendar = xmlDate.toGregorianCalendar();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date dt = calendar.getTime();
String ds1 = dt.toString();
System.out.println("ds1 = " + ds1);
String dateString = formatter.format(calendar.getTime());
System.out.println("dateString = " + dateString );
}
}
As YYYY represents year of the week and yyyy represents calendar year in simple date format.
More explanation here: Java SimpleDateFormat shifts Date by one year

Related

Convert String Date in yyyy-MM-dd into Java UtilDatein format yyyy-MM-dd [duplicate]

This question already has answers here:
want current date and time in "dd/MM/yyyy HH:mm:ss.SS" format
(11 answers)
return date type with format in java [duplicate]
(1 answer)
Closed 4 years ago.
I want to take a date value as String in the format yyyy-MM-dd and return a jabva util date in the same format.
for this I am using below code , but the result is coming as "Wed Sep 18 00:00:00 CEST 2013"
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String strdate = "2013-09-18";
Date utilDate = sdf.parse(strdate);
System.out.println(utilDate);
Do i need to consider the locale also ?
Please help to achieve this.
Thanks in advance
Please try below code.
You also have to format your simpleDateFormat object and pass utilDate object inside it to create formatted date as specified by you.
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateTest {
public static void main(String[] args) throws ParseException{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String strdate = "2013-09-18";
Date utilDate = sdf.parse(strdate);
String date=sdf.format(utilDate );
System.out.println(date);
}
}
We can also implement through Java8 like below:
import java.text.ParseException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class DateTest {
public static void main(String[] args) throws ParseException{
String strdate = "2013-09-18";
DateTimeFormatter formatter=DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate date = LocalDate.parse(strdate, formatter);
System.out.println(date.format(formatter));
}
}
or you can also use only LocalDate to change in java util like below.
import java.time.LocalDate;
public class TestCircle {
public static void main(String args[]){
String strdate = "2013-09-18";
LocalDate date = LocalDate.parse(strdate);
System.out.println(date);
}
}

How to convert current UTC Timezone to Indian Standard Time using Java [duplicate]

This question already has answers here:
Java : Cannot format given Object as a Date
(7 answers)
converting UTC date string to local date string inspecific format
(3 answers)
Closed 4 years ago.
I am trying to convert current UTC time (time from my Linux server) using below code.
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
public class UtcToIst {
public static void main(String[] args) {
List<String> timeZones = new ArrayList<String>();
String ISTDateString = "";
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String utcTime = sdf.format(new Date());
System.err.println("utcTime: " + utcTime);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String pattern = "dd-MM-yyyy HH:mm:ss";
SimpleDateFormat formatter;
formatter = new SimpleDateFormat(pattern);
try {
String formattedDate = formatter.format(utcTime);
Date ISTDate = sdf.parse(formattedDate);
ISTDateString = formatter.format(ISTDate);
timeZones.add(utcTime+ ","+ ISTDateString);
} catch(Exception e) {
e.printStackTrace();
}
for(String i: timeZones) {
System.out.println(i);
}
}
}
When I execute the code, I get the below exception:
utcTime: 05-11-2018 12:55:28
java.lang.IllegalArgumentException: Cannot format given Object as a Date
at java.text.DateFormat.format(DateFormat.java:310)
at java.text.Format.format(Format.java:157)
at UtcToIst.main(UtcToIst.java:21)
I see that the UTC time being fetched correctly as: 05-11-2018 12:55:28
But the code is unable to parse the string into IST(Indian Standard Time).
I am unable understand how can I fix the problem.
Could anyone let me know what is the mistake I am making here and how can I sort it out ?
This line is useless and causes the error (utcTime is not a Date, it's a String).
String formattedDate = formatter.format(utcTime);
Just replace:
String formattedDate = formatter.format(utcTime);
Date ISTDate = sdf.parse(formattedDate);
With:
Date ISTDate = sdf.parse(utcTime);
Whole class:
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
public class UtcToIst {
public static void main(String[] args) {
List<String> timeZones = new ArrayList<String>();
String ISTDateString = "";
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String utcTime = sdf.format(new Date());
System.err.println("utcTime: " + utcTime);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String pattern = "dd-MM-yyyy HH:mm:ss";
SimpleDateFormat formatter;
formatter = new SimpleDateFormat(pattern);
try {
Date ISTDate = sdf.parse(utcTime);
ISTDateString = formatter.format(ISTDate);
timeZones.add(utcTime+ ","+ ISTDateString);
} catch(Exception e) {
e.printStackTrace();
}
for(String i: timeZones) {
System.out.println(i);
}
}
}
use LocalDateTime instead
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");
LocalDateTime now = LocalDateTime.now();
System.out.println(dtf.format(now));
Noteļ¼šthe #Benoit's answer produce the incorrect time result if the server timezone is not Indian timezone, Should set timezone to Indian explicitly.
First: Set correct timezone on SimpleDateFormat, Asia/Kolkata for Indian time.
Second: use utc formatter to parse the formatted time string to get the utc time instance.
Last: use Indian to format the utc time instance.
See below code:
SimpleDateFormat utcFormatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
utcFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
String utcTime = utcFormatter.format(new Date());
System.err.println("utcTime: " + utcTime);
Date utcTimeInstance = utcFormatter.parse(utcTime);
SimpleDateFormat indianFormatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
indianFormatter.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));
String indianTime = indianFormatter.format(utcTimeInstance);
System.err.println("indianTime: " + indianTime);
On my pc prints:
utcTime: 05-11-2018 13:42:31
indianTime: 05-11-2018 19:12:31

Convert String into Date java [duplicate]

This question already has answers here:
java does not parse for 'M dd, yyyy' date format
(4 answers)
Closed 7 years ago.
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormatter {
public static void main(String[] args) throws ParseException {
String testString = "14 September 11";
DateFormat df = new SimpleDateFormat("dd MMMM yy");
Date newDate = df.parse(testString);
}
}
Tell me, why do I have:
Exception in thread "main" java.text.ParseException: Unparseable date: "14 September 11"
at java.text.DateFormat.parse(DateFormat.java:357)
at com.testtask.ruslan.converter.DateFormatter.main(DateFormatter.java:17)
It will work for English locales, but for others languages it won't. Do not rely on default locale. You always should specify locale explicitly for such conversions:
With Locale.US it passes:
String testString = "14 September 11";
DateFormat df = new SimpleDateFormat("dd MMMM yy", Locale.US);
Date newDate = df.parse(testString);
With new Locale("ru", "RU") it fails:
String testString = "14 September 11";
DateFormat df = new SimpleDateFormat("dd MMMM yy", new Locale("ru", "RU"));
Date newDate = df.parse(testString);

The incredible java time machine [duplicate]

This question already has answers here:
java parsing string to date
(2 answers)
Closed 9 years ago.
What happens to my time/date using this sample code??
package date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class DateFormatTest
{
public static void main(String args[]) throws ParseException
{
final String pattern = "dd/MM/YYYY HH:mm";
final Locale locale = Locale.FRENCH;
final SimpleDateFormat formatter = new SimpleDateFormat(pattern, locale);
Date d = new Date();
System.out.println("Today: " + d);
String parsedDate = formatter.format(d);
System.out.println("Today as string:" + parsedDate);
Date d2 = formatter.parse(parsedDate);
System.out.println("Today parsed back:" + d2);
}
}
Output:
Today: Fri Jun 28 16:28:04 CEST 2013
Today as string:28/06/2013 16:28
Today parsed back:Mon Dec 31 16:28:00 CET 2012 >>> ????
pattern = "dd/MM/YYYY HH:mm";
should be
pattern = "dd/MM/yyyy HH:mm";
See JavaDoc.
But note that this code as you posted does not even run on my Eclipse:
java.lang.IllegalArgumentException: Illegal pattern character 'Y'
Ah, Y is added in Java 7. But it is weekyear.
Little explanation, but is only a guessing, correct me if I'm wrong.
As the explanation of week year I guess that parsing the week year of 2013 (due to the wrong pattern 2013 -> YYYY ) is somehow setting the whole date to the first week year of the 2013, that is Monday 31/12/2012.

convert string date to a date object [duplicate]

This question already has answers here:
How to convert String object to Date object? [duplicate]
(8 answers)
Closed 9 years ago.
How can this 11/03/2009-20:06:16 to a Date object so I can compare two dates. I keep getting java.lang.IllegalArgumentException: Cannot format given Object as a Date error if I use below implementation.. I need the output to be date object with format Tue Jul 14 01:32:31 2009
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Dateaf {
/**
* #param args
* #throws ParseException
*/
public static void main(String[] args) throws ParseException {
// TODO Auto-generated method stub
String text = "11/03/2009-20:06:16";
SimpleDateFormat dateParser = new SimpleDateFormat("MM/dd/yyyy-hh:mm:ss");
Date date = dateParser.parse(text);
System.out.println(date);
}
}
sdf.format() takes a Date object and returns a String. You are passing a String to it.
You are very close, just drop the call to format:
Date date = sdf.parse(text);
So:
String text = "11-03-2009 20:06:16";
SimpleDateFormat dateParser = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss");
//^^ capital H for 24 hour
Date date = dateParser.parse(text);
And to print (from your comment in the format "Tue Jul 14 01:32:31 2009"):
SimpleDateFormat dateFormatter = new SimpleDateFormat("EE MM dd HH:mm:ss yyyy");
System.out.println(dateFormatter.format(date));
The SimpleDateFormat javadoc is an excellent reference for formats.
EDIT
After OP's edits here is a full example
public static void main(String[] args) throws ParseException {
final String text = "11/03/2009-20:06:16";
final SimpleDateFormat dateParser = new SimpleDateFormat("MM/dd/yyyy-HH:mm:ss");
final Date date = dateParser.parse(text);
final SimpleDateFormat dateFormatter = new SimpleDateFormat("EE MMM dd HH:mm:ss yyyy");
System.out.println(dateFormatter.format(date));
}
Output:
Tue Nov 03 20:06:16 2009
Java has the text package which gives us the predefined class text
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) throws Exception{
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Date today = df.parse("20/12/2005");
System.out.println("Today = " + df.format(today));
}
}
There is another way of doing this
String date = "2000-11-01";
java.sql.Date javaSqlDate = java.sql.Date.valueOf(date);

Categories