How to get date from date time in java - java

This is my date string,
String dd = "Nov-08-2019 07:00:28.190 UTC(+0000)";
I want to get only date with "yyyy-MM-dd" format.
How can I get date with this format.
I tried with below code, But it's not working.
String dd = "Nov-08-2019 07:00:28.190 UTC(+0000)";
Date date = null;
try {
date = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss Z").parse(dd);
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String newstr = new SimpleDateFormat("yyyy-MM-dd").format(date);
System.out.println("\n"+newstr+"\n");

java.time
Using java.time, the modern Java date and time API, it’s pretty simple when you know how:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(
"MMM-dd-uuuu HH:mm:ss.SSS zzz(xx)", Locale.ROOT);
String dd = "Nov-08-2019 07:00:28.190 UTC(+0000)";
LocalDate date = LocalDate.parse(dd, formatter);
System.out.println(date);
Output is:
2019-11-08
As we can see, your string is in UTC. I have assumed that you also want your date in UTC. If not, we need to parse into a ZonedDateTime, convert to your desired zone and then format into your desired output format with only the date.
I assumed that UTC(+0000) is a time zone abbreviation followed by an offset in brackets.
The date and time classes that you were trying to use, Date and SimpleDateFormat, are poorly designed and long outdated, the latter in particular notoriously troublesome. You should not use them. java.time is so much nocer to work with.
What went wrong in your code?
MM is for two-digit month number, for example 11 for November or 08 for August. For month abbreviation like Nov you need MMM.
Z is for offset like +0000. While this does appear in your string, the text UTC comes before it. Edit: Confusingly SimpleDateFormat parses UTC as time zone and then ignores the remainder of the string. I for my part shouldn’t want to rely on this behaviour.
I recommend you specify a locale with your formatter to control which language it expects in the string. With MMM for month abbreviation, if you rely on the default locale and it happens to be Welsh, your formatter will expect Tach for November.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Related question: Why can't this SimpleDateFormat parse this date string?

Don't use SimpleDateFormat and Date classes those are legacy, Use java-8 modern date time API classes, First create DateTimeFormatter with the input format date
String dd = "Nov-08-2019 07:00:28.190 UTC(+0000)";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM-dd-uuuu HH:mm:ss.SSS zzz(Z)");
And then use OffsetDateTime to parse it with particular offset (In your case UTC)
OffsetDateTime dateTime = OffsetDateTime.parse(dd,formatter);
And then get the LocalDate
System.out.println(dateTime.toLocalDate());

The pattern you provide in the SimpleDateFormatter class constructor should match with the provided output.
e.g. since you are providing month as three letters, use 3 M's in the pattern.
String dd = "Nov-08-2019 07:00:28";
Date date = null;
try {
date = new SimpleDateFormat("MMM-dd-yyyy HH:mm:ss").parse(dd);
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String newstr = new SimpleDateFormat("yyyy-MM-dd").format(date);
System.out.println("\n"+newstr+"\n");
}

String dd = "Nov-08-2019 07:00:28.190 UTC(+0000)";
Date date = null;
try {
date = new SimpleDateFormat("MMM-dd-yyyy hh:mm:ss.S z").parse(dd);
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String newstr = new SimpleDateFormat("yyyy-MM-dd").format(date);
System.out.println("\n"+newstr+"\n");
This might help you.

Your input string is
String dd = "Nov-08-2019 07:00:28.190 UTC(+0000)";
You want is
yyyy-MM-dd
first it is not possible you should be getting yyyy-MMM-dd for that the code will be
String dd = "Nov-08-2019 07:00:28.190 UTC(+0000)";
Date date = null;
try {
date = new SimpleDateFormat("MMM-dd-yyyy HH:mm:ss Z").parse(dd);
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String newstr = new SimpleDateFormat("yyyy-MM-dd").format(date);
System.out.println("\n"+newstr+"\n");

"Nov" is known as "MMM" format so it will throw the exception.
Try this code: https://onlinegdb.com/H1keFI5oS
import java.util.Date;
import java.text.SimpleDateFormat;
public class Main
{
public static void main(String []args){
String dd = "Nov-08-2019 07:00:28.190 UTC(+0000)";
Date date = null;
try {
date = new SimpleDateFormat("MMM-dd-yyyy HH:mm:ss").parse(dd);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String newstr = new SimpleDateFormat("yyyy-MM-dd").format(date);
System.out.println("\n"+newstr+"\n");
}
}

Related

How can i get simple yyyy-MM-dd out of this date?

I have String with date format dd.MM.yyyy, and I want to upload it to my MS SQL server, but the required format is yyyy-MM-dd. I tried this but it doesn't work like I want to.
String expDate = mDatePickerBtn.getText().toString();
Date date = null;
SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy");
try {
date = format.parse(expDate);
expDate = date.getYear() + "-" + date.getMonth() + "-" + date.getDay();
} catch (ParseException e) {
e.printStackTrace();
}
For example if I pass 31.12.2032 to the expDate, the date variable will cointain "Fri Dec 31 00:00:00: GMT+01:00 2032", and the expDate will contain "132-11-5" and I don't even know why.
I would use DateTimeFormatter but my minimal API level is 24.
My question is: where did I make mistake or how else can I get correct format out of this?
Go compile your app with Android Gradle Plugin 4.0.0+ and use java.time then like this:
public static void main(String[] args) {
// get / provide the String to be parsed
String expDate = "31.12.2032";
// provide a pattern that parses such a date
String pattern = "dd.MM.uuuu";
// create a DateTimeFormatter with this pattern
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(pattern);
// parse the String with the DateTimeFormatter
LocalDate expLocalDate = LocalDate.parse(expDate, dtf);
// print the default format of a LocalDate
System.out.println(expLocalDate);
// print the LocalDate using the pattern created for parsing
System.out.println(expLocalDate.format(dtf));
// create a totally different DateTimeFormatter inline and format the date differently
System.out.println(expLocalDate.format(DateTimeFormatter.ofPattern("EEE, dd 'of' MMMM uuuu",
Locale.ENGLISH)));
}
The output would be this:
2032-12-31
31.12.2032
Fri, 31 of December 2032
Try this way
String expDate = mDatePickerBtn.getText().toString();
Date date = null;
SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy");
try {
date = format.parse(expDate);
SimpleDateFormat format1 = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH);
format1.format(date);
expDate = format1.format(date);
} catch (ParseException e) {
e.printStackTrace();
}

java.text.ParseException: Unparseable date: "2018-05-23T06:39:37+0000"

I'm trying to create a Date from a String I receive from the server. The String is:
2018-05-23T06:39:37+0000
So the correct format should be:
yyyy-MM-dd'T'HH:mm:ss.SSSZ
Here is my code:
String createdDate = comment.getCreatedDateTime();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.US);
try {
Date parsedDate = simpleDateFormat.parse(createdDate);
createdDate = parsedDate.toString();
} catch (ParseException ex) {
ex.printStackTrace();
}
mCommentDate.setText(createdDate);
I don't know if there is any way to do this, because after that I would like to parse again to the next format:
dd/MM/yyyy hh:mm
I've tried to parse the original String using this last format directly but I'm getting the same exception.
Any suggestion?
I see you've solved your own problem with a little help from the comments, however I would suggest you seriously consider LocalDate, as the older Date classes are quite troublesome at times.
In fact, as your incoming value has a TimeZone, you'll need to use ZonedDateTime to parse your input.
String createdDate = "2018-05-23T06:39:37+0000";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ");
ZonedDateTime localDate = ZonedDateTime.parse(createdDate, formatter);
System.out.println(localDate.format(DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm")));
Output:
23/05/2018 06:39
The given input date String format
2018-05-23T06:39:37+0000
is incorrect so that you are getting ParseException since millisecond(SSS) part is missing from your date format yyyy-MM-dd'T'HH:mm:ss.SSSZ
So please try with
2018-05-23T06:39:37.235-0530
so below code should work
String createdDate = comment.getCreatedDateTime();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.US);
try {
Date parsedDate = simpleDateFormat.parse(createdDate);
createdDate = parsedDate.toString();
System.out.println(parsedDate.toString());
} catch (ParseException ex) {
ex.printStackTrace();
}
mCommentDate.setText(createdDate);
Ok, the first mistake (as you've pointed) is I didn't have milliseconds on the original String.
After removing "SSS" from the simpleDateFormat it works like a charm. So this is the final code:
String createdDate = comment.getCreatedDateTime();
SimpleDateFormat defaultDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.getDefault());
try {
Date parsedDate = defaultDateFormat.parse(createdDate);
SimpleDateFormat finalDateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm", Locale.getDefault());
createdDate = finalDateFormat.format(parsedDate);
} catch (ParseException ex) {
ex.printStackTrace();
}
mCommentDate.setText(createdDate);

Convert string with millisecond and timezone to Date

I have string in this format:
2017-04-06T09:29:12.225Z
I need it in date format i tried with:
private Date convertStringToDate(String dateString) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.sssZ");
Date convertedDate = new Date();
try {
convertedDate = dateFormat.parse(dateString);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return convertedDate;
}
But it showing Unparsable error?
Since Java 7 you can use
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");
The X stands for the ISO 8601 time zone, which may be simply Z (the zero time zone) or something like -08, -0800 or -08:00.
See also the table given in the javadoc of SimpleDateFormat.
Try milliseconds should be capital S:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
Try
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
The milliseconds should be capital S, and the Z should be in single quotes:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");

Convert `Java.lang.String` TO `oracle.sql.TIMESTAMPTZ`

I have these following Java.lang.String values that represents String value of TIMESTAMPTZ. I need to convert these Java.lang.String TO oracle.sql.TIMESTAMPTZ.
"2016-04-19 17:34:43.781 Asia/Calcutta",
"2016-04-30 20:05:02.002 8:00",
"2003-11-11 00:22:15.0 -7:00",
"2003-01-01 02:00:00.0 -7:00",
"2007-06-08 15:01:12.288 Asia/Bahrain",
"2016-03-08 17:17:35.301 Asia/Calcutta",
"1994-11-24 11:57:17.303"
I tried it by many ways.
Sample 1:
Tried it by using SimpleDateFormat
String[] timeZoneValues = new String[]{"2016-04-19 17:34:43.781 Asia/Calcutta", "2016-04-30 20:05:02.002 8:00", "2003-11-11 00:22:15.0 -7:00", "2003-01-01 02:00:00.0 -7:00", "2007-06-08 15:01:12.288 Asia/Bahrain", "2016-03-08 17:17:35.301 Asia/Calcutta", "1994-11-24 11:57:17.303"};
for(String timeZoneValue: timeZoneValues){
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS XXX");
try {
simpleDateFormat.parse(timeZoneValue);
} catch (ParseException e) {
e.printStackTrace();
}
}
That thrown an Exception:
java.text.ParseException: Unparseable date: "2016-04-19 17:34:43.781 Asia/Calcutta"
at java.text.DateFormat.parse(DateFormat.java:357)
Sample 2:
Tried it by converting these String values directly into Timestamp or oracle.sql.TIMESTAMPTZ
String parse = "2016-04-19 17:34:43.781 8:00";
try {
Timestamp timestamp = Timestamp.valueOf("2016-04-19 17:34:43.781 8:00");
}catch (Exception ex){
ex.printStackTrace();
}
Exception:
java.lang.NumberFormatException: For input string: "781 8:000"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.parseInt(Integer.java:527)
at java.sql.Timestamp.valueOf(Timestamp.java:253)
Sample 3:
String parse = "2016-04-19 17:34:43.781 Asia/Calcutta";
DateTimeFormatter dateTimeFormatter = ISODateTimeFormat.dateTimeNoMillis();
DateTime dateTime = dateTimeFormatter.parseDateTime(parse);
Timestamp timeStamp = new Timestamp(dateTime.getMillis());
Exception:
Invalid format: "2016-04-19 17:34:43.781 Asia/Calcutta" is malformed at " 17:34:43.781 Asia/Calcutta"
Sample 4:
try {
TIMESTAMPTZ timestamptz = new TIMESTAMPTZ(connection, (String) colValue);
}catch (Exception ex){
ex.printStackTrace();
}
Exception:
java.lang.IllegalArgumentException: Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff]
at java.sql.Timestamp.valueOf(Timestamp.java:249)
at oracle.sql.TIMESTAMPTZ.toBytes(TIMESTAMPTZ.java:1919)
at oracle.sql.TIMESTAMPTZ.<init>(TIMESTAMPTZ.java:253)
I am trying to insert the TIMESTAMPTZ value into Oracle database using Apache Metamodel and I have Java 1.7 installed on my system.
Your timestamps are not in a standard java parseable formats. So in order to parse them you need to write custom code for handling such formats.
Couple of observations:
Asia/Calcutta is not a valid Parseable TimeZone, hence you need some
mechanism to get corresponding timezone.
8:00 is also not a valid Parseable Timezone in java, hence you need
some mechanism to format it in a valid value +08:00
Keeping above points in mind, following code will do the needful for you.
SimpleDateFormat dateFormatTZGeneral = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS z");
SimpleDateFormat dateFormatTZISO = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS XXX");
SimpleDateFormat dateFormatWithoutTZ = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
String[][] zoneStrings = DateFormatSymbols.getInstance().getZoneStrings();
Date date = null;
String[] timeStampSplits = timestamp.split(" ");
if(timeStampSplits.length>2) {
String timezone = timeStampSplits[2];
//First Case Asia/Calcutta
if(Character.isAlphabetic(timezone.charAt(timezone.length()-1))) {
for(String[] zoneString: zoneStrings) {
if(zoneString[0].equalsIgnoreCase(timezone)) {
timeStampSplits[2] = zoneString[2];
break;
}
}
timestamp = createString(timeStampSplits," ");
date = getDate(timestamp, dateFormatTZGeneral);
} else {
//Second Case 8:00
timeStampSplits[2] = formatTimeZone(timeStampSplits[2]);
timestamp = createString(timeStampSplits," ");
date = getDate(timestamp, dateFormatTZISO);
}
} else {
// Third Case without timezone
date = getDate(timestamp, dateFormatWithoutTZ);
}
System.out.println(date);
TIMESTAMPTZ oraTimeStamp = new TIMESTAMPTZ(<connection object>,new java.sql.Timestamp(date.getTime());
Above code uses following utility methods
private static Date getDate(String timestamp, SimpleDateFormat dateFormat) {
Date date = null;
try {
date = dateFormat.parse(timestamp);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return date;
}
private static String createString(String[] contents, String separator) {
StringBuilder builder = new StringBuilder();
for (String content : contents) {
builder.append(content).append(separator);
}
builder.deleteCharAt(builder.length()-separator.length());
return builder.toString();
}
private static String formatTimeZone(String timeZone) {
String[] timeZoneSplits = timeZone.split(":");
DecimalFormat formatter = new DecimalFormat("+##;-#");
formatter.setMinimumIntegerDigits(2);
timeZoneSplits[0] = formatter.format(Integer.parseInt(timeZoneSplits[0]));
return createString(timeZoneSplits, ":");
}
This code is specifically written to cater your timestamp examples, any deviation might not be handled by this and it will need more customization.
Hope this helps you.
You have to parse the date according to the data coming i.e dynamic. For information about What constant used by android you have to follow the link
and in case of Java you have to follow link
Here is the code snippet of some different format
Sample 1
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS zzzz");
Date date = null;
try {
date = sdf.parse("2016-04-19 17:34:43.781 Pacific Standard Time");
Log.e("date",""+date);
} catch (ParseException e) {
e.printStackTrace();
}
sdf.setTimeZone(TimeZone.getTimeZone("IST"));
System.out.println(sdf.format(date));
Sample 2
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS z");
Date date = null;
try {
date = sdf.parse("2016-04-19 17:34:43.781 -08:00");
Log.e("date",""+date);
} catch (ParseException e) {
e.printStackTrace();
}
sdf.setTimeZone(TimeZone.getTimeZone("IST"));
System.out.println(sdf.format(date));
Sample 3
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date date = null;
try {
date = sdf.parse("2016-04-19 17:34:43.781");
Log.e("date",""+date);
} catch (ParseException e) {
e.printStackTrace();
}
sdf.setTimeZone(TimeZone.getTimeZone("IST"));
System.out.println(sdf.format(date));
So as per these three set of sample you can parse any type of date time except the one format i.e "2016-04-19 17:34:43.781 Asia/Calcutta" as the time zone Asia/Calcutta or Asia/Bahrain can not get read by android or java. This is the format which gets supported by PHP as per my understanding. SO If you want to parse these type of format then I guess you have to write your custom SimpleDateFormat and have to identify these content and perform the calculation according to your need.
The Timestamp strings are in different format,
Ex-Here SimpleDateFormat uses pattern :
'yyyy-MM-dd HH:mm:ss.SSS XXX'
where X is to represent timezone in [ISO 8601 time zone][1] format.For this
timezone valid Timestamp Strings are (-08; -0800; -08:00).So,'Asia/Kolkata'
will not be parsed for Sample 1.
There are three type of Timezone pattern to be assigned to SimpleDateFormat.
**'Z'** - RFC 822 time zone.
**'z'** - General time zone.
**'X'** - ISO 8601 time zone.
So,either use different SimpleDateFormat's,or convert Timezone of all timestamp into same pattern of timezone and use a single SimpleDateFormat.

Convert string to date format in android

I'm trying to convert string to date format.I trying lot of ways to do that.But not successful. my string is "Jan 17, 2012". I want to convert this as " 2011-10-17".
Could someone please tell me the way to do this? If you have any worked through examples, that would be a real help!
try {
String strDate = "Jan 17, 2012";
//current date format
SimpleDateFormat dateFormat = new SimpleDateFormat("MMM dd, yyyy");
Date objDate = dateFormat.parse(strDate);
//Expected date format
SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd");
String finalDate = dateFormat2.format(objDate);
Log.d("Date Format:", "Final Date:"+finalDate)
} catch (Exception e) {
e.printStackTrace();
}
String format = "yyyy-MM-dd";
SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US);
System.err.format("%30s %s\n", format, sdf.format(new Date(0)));
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
System.err.format("%30s %s\n", format, sdf.format(new Date(0)));
Which produces this output when run in the PDT time zone:
yyyy-MM-dd 1969-12-31
yyyy-MM-dd 1970-01-01
For more info look at here
I suggest using Joda Time, it's the best and simplest library for date / dateTime manipulations in Java, and it's ThreadSafe (as opposed to the default formatting classes in Java).
You use it this way:
// Define formatters:
DateTimeFormatter inputFormat = DateTimeFormat.forPattern("MMM dd, yyyy");
DateTimeFormatter outputFormat = DateTimeFormat.forPattern("yyyy-MM-dd");
// Do your conversion:
String inputDate = "Jan 17, 2012";
DateTime date = inputFormat.parseDateTime(inputDate);
String outputDate = outputFormat.print(date);
// or:
String outputDate = date.toString(outputFormat);
// or:
String outputDate = date.toString("yyyy-MM-dd");
// Result: 2012-01-17
It also provides plenty of useful methods for operations on dates (add day, time difference, etc.). And it provides interfaces to most of the classes for easy testability and dependency injection.
Why do you want to convert string to string try to convert current time in milisecond to formated String,
this method will convert your milisconds to a data formate.
public static String getTime(long milliseconds)
{
return DateFormat.format("MMM dd, yyyy", milliseconds).toString();
}
you can also try DATE FORMATE class for better understanding.
You can't convert date from one format to other. while you are taking the date take you have take the date which ever format the you want. If you want the date in yyyy-mm-dd. You can get this by using following way.
java.util.Calendar calc = java.util.Calendar.getInstance();
int day = calc.get(java.util.Calendar.DATE);
int month = calc.get(java.util.Calendar.MONTH)+1;
int year = calc.get(java.util.Calendar.YEAR);
String currentdate = year +"/"+month +"/"+day ;
public static Date getDateFromString(String date) {
Date dt = null;
if (date != null) {
for (String sdf : supportedDateFormats) {
try {
dt = new Date(new SimpleDateFormat(sdf).parse(date).getTime());
break;
} catch (ParseException pe) {
pe.printStackTrace();
}
}
}
return dt;
}
Try this simple method:
fun getFormattedDate(strDate:String): String {
try {
val dateFormat = SimpleDateFormat("dd/mm/yyyy")//old format
val dateFormat2 = SimpleDateFormat("mm/dd/yyyy")//require new formate
val objDate = dateFormat.parse(strDate)
return dateFormat2.format(objDate)
} catch (e:Exception) {
return ""
}
}

Categories