Java string to date with negative number [duplicate] - java

This question already has answers here:
Java string to date conversion
(17 answers)
Closed 5 years ago.
I am trying to convert dates of the format
07/Mar/2004:16:56:39 -0800
to a date object. I'm not sure what that format's name even is but its used in tomcat access logs. Can someone please help me out?
SimpleDateFormat f = new SimpleDateFormat("dd-MMM-yyyy:HH:mm:ss");
Date d = f.parse("07/Mar/2004:16:56:39 -0800"); // Throws exception.
System.out.println(d.getTime());

The format string should match the input. In particular, the separator must match.
Also, your format string is missing the time zone part to match against the -0800.
Since your input uses English month name, you should explicitly specify that, e.g. using Locale.US.
SimpleDateFormat f = new SimpleDateFormat("dd/MMM/yyyy:HH:mm:ss Z", Locale.US);
Date d = f.parse("07/Mar/2004:16:56:39 -0800");
System.out.println(d);
Since I'm in Eastern time zone, that prints:
Sun Mar 07 19:56:39 EST 2004
You should however use the new java.time classes instead.
Since the input string has a time zone offset, that means you should parse the string to an OffsetDateTime, using a DateTimeFormatter:
DateTimeFormatter f = DateTimeFormatter.ofPattern("dd/MMM/uuuu:HH:mm:ss Z", Locale.US);
OffsetDateTime dt = OffsetDateTime.parse("07/Mar/2004:16:56:39 -0800", f);
System.out.println(dt);
Output is:
2004-03-07T16:56:39-08:00

You need to add the time zone to your date format and change the format to your input string (/ instead of -):
SimpleDateFormat f = new SimpleDateFormat("dd/MMM/yyyy:HH:mm:ss Z", Locale.US);
See the docs: https://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html

You have a typo in the line:
Date d = f.parse("07/Mar/2004:16:56:39 -0800");
The format for the date is "dd-MMM-yyyy:HH:mm:ss". You need to replace the "/" with "-". Additionally, you need to surround your parse function with a try-catch block as follows:
SimpleDateFormat f = new SimpleDateFormat("dd-MMM-yyyy:HH:mm:ss");
Date d;
try {
d = f.parse("07-Mar-2004:16:56:39");
System.out.println(d.getTime());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Check out this link to learn more about the SimpleDateFormat Class:
http://www.xyzws.com/javafaq/how-to-use-simpledateformat-class-formating-parsing-date-and-time/142

Related

converting a date format in java [duplicate]

This question already has answers here:
Parsing ISO-8601 DateTime with offset with colon in Java
(4 answers)
Closed 3 years ago.
I have a date value: - 2019-09-30T00:00:00.000+05:30
I want to convert into the format - dd MMM yyyy
I have the code:
public static String parseDateAndTimeStringCust(String datestring) {
if(datestring.length()>=10){
SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
String fDate = new SimpleDateFormat("dd MMM yyyy").format(dateFormat2.parse(datestring));
return fDate;
} catch (ParseException ex) {
ex.printStackTrace();
}
}
return datestring;
}
Analysis:
My dateFormat2 I am using is wrong
Question:
What is the correct data format i have to use so that I can get the
result in the format dd MMM yyyy
What is the proper reference I can use in future to build such date
formats
You should use classes from the java.time package.
This is what you're looking for.
String str = "2019-09-30T00:00:00.000+05:30";
OffsetDateTime dt = OffsetDateTime.parse(str);
String out = dt.format(DateTimeFormatter.ofPattern("dd MMM yyyy"));
System.out.println(out);
Note that the actual output depends on your locale, but then you could supply the Locale as the second argument to DateTimeFormatter.ofPattern.
Also note that the single-argument version of OffsetDateTime.parse implies the ISO_OFFSET_DATE_TIME format.
Furthermore, whether the actual output of abovementioned method is accurate, depends on how you want to handle the timezone offset, i.e. whether you want to convert it to UTC or ignore it. For instance, the timestamp 2019-09-30T00:00:00.000+05:30 actually falls on the 29th of September if converted to UTC (the time is then 2019-09-29T18:30:00.000Z).
DateTimeFormatter
The documentation of the DateTimeFormatter class contains detailed information about the formatting symbols and how they are parsed. There are many predefined formats for well-known and commonly used patterns, for example ISO_OFFSET_DATE_TIME conforming with the ISO 8601 standard.
public static String parseDateAndTimeStringCust(String datestring) {
Date dataFormated = null;
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
try {
dataFormated = dateFormat.parse(datestring);
} catch (ParseException ex) {
ex.printStackTrace();
}
return dataFormated.toString();
}
Try changing following line:
SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
To:
SimpleDateFormat dateFormat2 = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");

Java Date Parsing from string

I'm trying to parse a String into Data, I create the DataParser, in according to date format, the code I wrote is this:
String date_s = "04-May-2017 17:28:27";
DateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
Date date;
try {
date = formatter.parse(date_s);
System.out.println(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
When I execute this, I got always an exception
java.text.ParseException: Unparseable date: "04-May-2017 17:28:27"
I don't understand why the data is not parsed, someone can help me?
This thread of answers would not be complete without the modern solution. These days you should no longer use Date and SimpleDateFormat, but switch over to the newer date and time classes:
DateTimeFormatter formatter
= DateTimeFormatter.ofPattern("dd-MMM-yyyy HH:mm:ss", Locale.ENGLISH);
LocalDateTime dateTime;
try {
dateTime = LocalDateTime.parse(date_s, formatter);
System.out.println(dateTime);
} catch (DateTimeParseException e) {
System.err.println(e);
}
This prints
2017-05-04T17:28:27
(LocalDateTime.toString() returns ISO 8601 format) If leaving out Locale.ENGLISH, on my computer I get
Text '04-May-2017 17:28:27' could not be parsed at index 3
Index 3 is where it say May, so the message is somewhat helpful.
LocalDateTime and DateTimeFormatter were introduced in Java 8, but have also been backported to Java 6 and 7.
the string you want to parse is local dependent (the word May is English), so the jvm is not able to infer that may is the month of may in English
define the formatter using the constructor qith the locale.
DateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss",Locale.ENGLISH);
You need another constructor with a Locale that supports MMM (May)
DateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss",Locale.US)
or using standard format dd-MM-yyyy with month digits.
(Sorry, in the meantime the answer was already posted)

How to convert date format 2017-02-08 00:00:00.0 to 08/02/2017 in java? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Java string to date conversion
(17 answers)
Closed 6 years ago.
I want to convert Date format from 2017-02-08 00:00:00.0 to dd/MM/yyyy(08/02/2017). I tried with the following code.
String dateInString =bean.getDate();
Date date = null;
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
if (bean.getDate().matches("^[0-9]{2,4}(-[0-9]{1,2}){2}\\s[0-9]{1,2}(:[0-9]{1,2}){2}\\.[0-9]{1,}$")) {
try {
date = formatter.parse(dateInString);
} catch (ParseException e) {
e.printStackTrace();
}
}
But I am getting NullPointerException in date = formatter.parse(dateInString); line.
You can use the below code:
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
SimpleDateFormat format2 = new SimpleDateFormat("dd/MM/yyyy");
String date = "2017-02-08 00:00:00.0";
try {
Date dateNew = format1.parse(date);
String formatedDate = format2.format(dateNew);
System.out.println(formatedDate);
} catch (ParseException e) {
e.printStackTrace();
}
String dateInString = "2017-02-08 00:00:00.0";
Date date = null;
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
try {
date = formatter.parse(dateInString);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat formatter2 = new SimpleDateFormat("dd/MM/yyyy");
System.out.println(formatter2.format(date));
The other Answers are outdated, using troublesome old date-time classes such as SimpleDateFormat.these old classs are now legacy, supplanted by the java.time classes.
LocalDateTime
Parse your input string as a LocalDateTime as the input lacks any indication of offset-from-UTC or time zone.
The input string nearly complies with standard ISO 8601 formatting. The standard formats are used by default with the java.time classes. Replace the SPACE in middle with a T.
String input = "2017-02-08 00:00:00.0".replace( " " , "T" );
LocalDateTime ltd = LocalDateTime.parse( input );
LocalDate
Extract a date-only object.
LocalDate ld = ltd.toLocalDate();
DateTimeFormatter
Generate a string representing that object's value. Specify your desired formatting pattern.
Locale l = Locale.US ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" ).withLocale( l );
String output = ld.format( f );
create a SimpleDateFormat object and use it to parse Strings to Date and to format Dates to Strings. If you've tried SimpleDateFormat and it didn't work, then please show your code and any errors you may receive.
MM and mm both are different. MM points Month, mm points minutes
Some example for months
'M' - 7 (without prefix 0 if it is single digit)
'M' - 12
'MM' - 07 (with prefix 0 if it is single digit)
'MM' - 12
'MMM' - Jul (display with 3 character)
'MMMM' - December (display with full name)
Some example for minutes
'm' - 3 (without prefix 0 if it is single digit)
'm' - 19
'mm' - 03 (with prefix 0 if it is single digit)
'mm' - 19

SimpleDateFormat Always returning 12.30 AM [duplicate]

This question already has answers here:
Simple date formatting giving wrong time
(4 answers)
Closed 7 years ago.
I am trying to utilise the Calendar apart from implementing my own logic.
I am setting the Calendar value and trying to get the time in a format, below is the code
String timeValue = "06/11/2015 06:30 pm";
SimpleDateFormat sdf= new SimpleDateFormat("dd/MM/yyyy HH:mm a");
Calendar calendar = Calendar.getInstance();
try {
calendar.setTime(sdf.parse(timeValue));
Logger.d(TAG, "Hour is = " + calendar.get(Calendar.HOUR));
SimpleDateFormat slotTime = new SimpleDateFormat("hh:mma");
SimpleDateFormat slotDate = new SimpleDateFormat(", dd/MM/yy");
Logger.d(TAG, " Date = " + slotDate.format(calendar.getTime()) + " Time is = " + slotTime.format(calendar.getTime()));
}catch (ParseException parseEx){
parseEx.printStackTrace();
}
I am expecting slotTime.format(calendar.getTime())) should return 6.30 PM while it is returning 12.30 AM.
How can I get the desired output which is 6.30 PM , What mistake I am doing
Your code is OK. The mistake is on the datetime mask:
The ".SSS" field is too much. This is only to expect for milliseconds, and, as far as I can see, you do not expect milliseconds in your input string.
The "HH" mask should be "hh" for 1-12 hours format.
Thus, let it be:
SimpleDateFormat sdf= new SimpleDateFormat("dd/MM/yyyy hh:mm a");
You have to remove milliseconds from your Simple Date Format (SSS).
I get a java.text.ParseException running your code.
Try using a Simple Date Format string of "dd/MM/yyyy HH:mm a"
you have an error with the String in the time format
String timeValue = "06/11/2015 06:30 pm";
SimpleDateFormat sdf= new SimpleDateFormat("dd/MM/yyyy hh:mm a.SSS");
a.SSS // .SSS is for Millisenconds which is not correct in the String you are trying to parse.
I removed it and worked fine for me.
Take a look at DateFormat.getTimeInstance(), DateFormat.getDateInstance() and DateFormat.getDateTimeInstance() as these methods return a DateFormat which will honor the users local settings (e.g. 12/24 hour system or date formats like 2016/01/01 or 01.01.2016). This is very important if you plan to release your app in multiple languages. Note that these methods also take a int as parameter with which you can style the resulting format (e.g. short format).
See here for more details.
A complete example would llok like this (creates a String like 3:04 PM on devices with English language and 15:04 on devices with e.g. German language):
String s = DateFormat.getTimeInstance(DateFormat.SHORT, Locale.getDefault()).format(new Date()); // Creates a String like 3:04 PM

How do I create the java date object without time stamp [duplicate]

This question already has answers here:
Java program to get the current date without timestamp
(17 answers)
Closed 6 years ago.
I want to create a Date object without a TimeZone (eg : 2007-06-21). Is this possible?
When I use the following method it prints like Thu Jun 21 00:00:00 GMT 2007
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
TimeZone timeZone = TimeZone.getTimeZone("GMT");
timeZone.setDefault(timeZone);
sdf.setTimeZone(timeZone);
Date pickUpDate = sdf.parse("2007-06-21");
System.out.println(pickUpDate);
If you want to format a date, you need to use DateFormat or something similar. A Date is just an instant in time - the number of milliseconds since the Unix epoch. It doesn't have any idea of time zone, calendar system or format. The toString() method always uses the system local time zone, and always formats it in a default way. From the documentation:
Converts this Date object to a String of the form:
dow mon dd hh:mm:ss zzz yyyy
So it's behaving exactly as documented.
You've already got a DateFormat with the right format, so you just need to call format on it:
System.out.println("pickUpDate" + sdf.format(pickUpDate));
Of course it doesn't make much sense in your sample, given that you've only just parsed it - but presumably you'd normally be passing the date around first.
Note that if this is for interaction with a database, it would be better not to pass it as a string at all. Keep the value in a "native" representation for as much of the time as possible, and use something like PreparedStatement.setDate to pass it to the database.
As an aside, if you can possibly change to use Joda Time or the new date/time API in Java 8 (java.time.*) you'll have a much smoother time of it with anything date/time-related. The Date/Calendar API is truly dreadful.
This is the toString() of the java.util.Date
public String toString() {
// "EEE MMM dd HH:mm:ss zzz yyyy";
BaseCalendar.Date date = normalize();
StringBuilder sb = new StringBuilder(28);
int index = date.getDayOfWeek();
if (index == gcal.SUNDAY) {
index = 8;
}
convertToAbbr(sb, wtb[index]).append(' '); // EEE
convertToAbbr(sb, wtb[date.getMonth() - 1 + 2 + 7]).append(' '); // MMM
CalendarUtils.sprintf0d(sb, date.getDayOfMonth(), 2).append(' '); // dd
CalendarUtils.sprintf0d(sb, date.getHours(), 2).append(':'); // HH
CalendarUtils.sprintf0d(sb, date.getMinutes(), 2).append(':'); // mm
CalendarUtils.sprintf0d(sb, date.getSeconds(), 2).append(' '); // ss
TimeZone zi = date.getZone();
if (zi != null) {
sb.append(zi.getDisplayName(date.isDaylightTime(), zi.SHORT, Locale.US)); // zzz
} else {
sb.append("GMT");
}
sb.append(' ').append(date.getYear()); // yyyy
return sb.toString();
}
So, if you will pass a Date and try to print it this will be printed out all the time.
Code:
Date date = new Date();
System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(date));
Date : Fri Apr 29 04:53:16 GMT 2016
Sample Output : 2016-04-29
Imports required :
import java.util.Date; //for new Date()
import java.text.SimpleDateFormat; // for the format change
System.out.println("pickUpDate " + sdf.format(pickUpDate));
You can use the above code to get formatted Date as String
Use this Code:
SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");
Date pickUpDate =sdf.parse("2007-06-21");
System.out.println("pickUpDate "+sdf.format(pickUpDate));
Hope it'll help you.
String your_format_date=sdf.format(pickUpDate);
System.out.println("pick Up Date " + your_format_date);
Date isn't a date. It's a timestamp. That's some impressive API design, isn't it?
The type you need is now java.time.LocalDate, added in Java 8.
If you can't use Java 8, you can use ThreeTen, a backport for Java 7.

Categories

Resources