How to convert ISOdate in String in JAVA - java

I am using MongoDB to save my data and in database i can see the date value like this
ISODate("2016-11-30T11:17:20.945Z")
but when i parse it in front-end it become like
createdOn : 1480582463992
I want to convert "ISODate("2016-11-30T11:17:20.945Z")" it in JAVA and not in js in such a way so that i can get string date value.
Thanks in advance
==============================================================
here is my java code
#Override
public List<Prescription> getcus(
String id, String cid) {
List<Prescription> listrescription = null;
listrescription = this.patientDBService.getPatientLastThreePrescription(id, cid);
Prescription prre = new Prescription();
for(Prescription i : listrescription){
//Date dates = new Date();
//i.getCreatedOn(); // getting the data from mongo like 1480582463992
//no clue what to do here to get ISO date as in string
}
return listrescription;
}

try this:
new Date("2016-11-30T11:17:20.945Z")

If you don't care about the time zone you can use this method to parse the date format like "2017-06-19T05:27:26.000Z"
private static String convertMongoDate(String val){
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
SimpleDateFormat outputFormat= new SimpleDateFormat("yyyy/MM/dd");
try {
String finalStr = outputFormat.format(inputFormat.parse(val));
System.out.println(finalStr);
return finalStr;
} catch (ParseException e) {
e.printStackTrace();
}
return "";
}

Related

How to display only time part from date time combination in java

I am new to Java. I am retrieving my first column from database in a String Array which represents data as:
2014-09-01 10:00:00.000
Now I want to display only time as:
10:00:00
How to do it?
My code to retrieve my Column is:
public String[] getChartTime() throws SQLException {
List < String > timeStr = new ArrayList < String > ();
String atime[] = null;
getConnection();
try {
con = getConnection();
String sql = "exec vcs_gauge #gauge_name=?,#first_rec_time=?,#last_rec_time=?";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("date is " + df.format(currentDate));
clstmt = con.prepareCall(sql);
clstmt.setString(1, "vs3_bag");
clstmt.setString(2, "2014-09-01 10:00:00");
clstmt.setString(3, "2014-09-01 11:00:00");
clstmt.execute();
rs = clstmt.getResultSet();
while (rs.next()) {
// Just get the value of the column, and add it to the list
timeStr.add(rs.getString(1));
}
} catch (Exception e) {
System.out.println("\nException in Bean in getDbTable(String code):" + e);
} finally {
closeConnection();
}
// I would return the list here, but let's convert it to an array
atime = timeStr.toArray(new String[timeStr.size()]);
for (String s: atime) {
System.out.println(s);
}
return atime;
}
Use SimpleDateFormat:
java.util.Date date = new java.util.Date();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
System.out.println(sdf.format(date));
If you have the date as a String, you can parse it to a java.util.Date in a step before:
SimpleDateFormat sdf = new SimpleDateFormat("YOUR_DATE_PATTERN");
Date date = sdf.parse(string);
Use patterns according to https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
If I have understood the question correctly 2014-09-01 10:00:00.000 is in a string and 10:00:00 has to be extracted from that. Given below is my solution.
First split the string with space as the delimiter.
Then from that take the second part of the string.
After that split the string again using . as the delimiter and take the first sting from that.
The above things are done using the line.
str.split("\\s")[1].split("\\.")[0];
COMPLETE CODE
String str = new String("2014-09-01 10:00:00.000");
String time = str.split("\\s")[1].split("\\.")[0];
System.out.print(time);
OUTPUT
10:00:00
For more details check the links given below:
String.split().
Patterns
Refer official Java docs here
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MyDate {
public static void main(String[] args){
DateFormat dateFormat = new SimpleDateFormat("hh:mm:ss a");
Date date = new Date();
String time=dateFormat.format(date);
System.out.println(time);
}
}
I got it,just use substring() as
while(rs.next()) {
// Just get the value of the column, and add it to the list
timeStr.add(rs.getString(1).substring(11,16));
}

How to reformat a string date in Java

I tacked this problem in VB awhile back, and thought I could easily translate it to Java. The input comes in as a string in the format:
"mm/dd/yyyy"
I want to change this to the following format:
"mm/dd/yy"
where the last two year digits are shown only. I wrote this VB awhile back, which does just that:
Function DateFormat(ByVal myDate As String) As String
Dim reformat As Date
reformat = Date.Parse(myDate, Nothing)
Return Format(reformat, "MM/dd/yy").ToString()
End Function
How can I do this exact same thing in Java, so that the date is reformatted correctly and returned as the string it originally was? I have something like this but it is not working properly:
public static String DateFormat(String myDate){
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
try{
Date formattedDate = formatter.parse(myDate);
return formattedDate.toString();
}catch(Exception e){
e.printStackTrace();
return null;
}
}
I am not sure how to make it the format I need, as I can't find anything similar to the Format() function VB has. Thanks in advance.
Try this :
public static String DateFormat(String myDate) throws ParseException {
SimpleDateFormat inFormat = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat outFormat = new SimpleDateFormat("MM/dd/yy");
Date parsedInDate = inFormat.parse(myDate);
return outFormat.format(parsedInDate);
}
At start, we declare two date formatters, then we create Date object from input String, and at the end we produce String in new format.
If I understand your question, you could use a pair of SimpleDateFormat(s)
private static final String formatIn = "MM/dd/yyyy";
private static final String formatOut = "MM/dd/yy";
private static final DateFormat sdfIn = new SimpleDateFormat(
formatIn);
private static final DateFormat sdfOut = new SimpleDateFormat(
formatOut);
public static String formatDateString(String dateIn)
throws ParseException {
return sdfOut.format(sdfIn.parse(dateIn));
}
public static void main(String[] args) {
try {
System.out.println(formatDateString("07/15/2014"));
} catch (ParseException e) {
e.printStackTrace();
}
}
Output is
07/15/14
SimpleDateFormat takes in a number of different formats. I believe the format you want is already built in and can be accessed like so...
Date date = new Date();
Format formatter = new SimpleDateFormat("MM/dd/yy");
String s = formatter.format(date);
System.out.println(s);
You've basically almost got it, just need to apply the new format.
public static String DateFormat(String myDate){
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
try{
Date date = formatter.parse(myDate);
formatter.applyPattern("MM/dd/yy");
return formatter.format(date);
}catch(Exception e){
e.printStackTrace();
return null;
}
}

changing date in string data type to java.sql.date data type

I have a method which reads the date that in form of srring and then conver it format in dd-MM-yy and finally return a string as shown below..
public static String getSimpleDate11(String dateString) {
if (dateString == null) {
return null;
}
DateFormat dfIn = new SimpleDateFormat("yyyy-MM-dd");
DateFormat dfOut = new SimpleDateFormat("dd-MM-yy");
try {
Date date = dfIn.parse(dateString);
return dfOut.format(date);
} catch (ParseException e) {
throw new RuntimeException(
"The date entered is invalid or has incorrect format"
+ dateString);
}
}
now I am calling this method from somewhere as shown below....
String formatteddate = DateUtility.getSimpleDate11(settlementDate);
now please advise how can I change this in java.sql.Date as I want to store the date in java.sql.Date..
java.sql.Date sd ------ here i want tio store the date finally
folks ple\ase advise .
java.sql.Date takes long value in its constructor (irrespective of the date format)
Date date=dfIn.parse(dateString);
new java.sql.Date(date.getTime());
should be equivalent as they represent the same Date object.

parsing only the Year in a DateFormat Java

I get a returned parsed JSON result with string values in the form of dates like "27-11-2012" which i parse to a date Object. my code for this is:
public Date stringToDateReport(String s){
//Log.d(TAG, "StringToDateReport here is " + s);
DateFormat format;
Date date = null;
//if(s.matches(""))
format = new SimpleDateFormat("dd-MMM-yyyy");
try {
date = (Date)format.parse(s);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
now my issue is, a feature has been implemented that sometimes the json only returns a year object like "2012" and is giving me an "ParseException: Unparseable date" as expected. I was thinking of using regex to match the string pattern and parse from there, but not sure how to do that. Any ideas and also anyway to parse only year in a DateFormat?
I'd try:
public Date stringToDateReport(String s){
DateFormat format;
Date date = null;
format = new SimpleDateFormat("dd-MM-yyyy");
if(s.length()==4) {
format = new SimpleDateFormat("yyyy");
}
try {
date = (Date)format.parse(s);
} catch (ParseException e) {
//you should do a real logging here
e.printStackTrace();
}
return date;
}
The logic behind is to check if the string is only 4 long, then apply the different format. In this case, this easy method is sufficient, but in other methods, the use of regexes might be required.
Try this code
public Date stringToDateReport(String s){
//Log.d(TAG, "StringToDateReport here is " + s);
DateFormat format;
Date date = null;
if(s.indexOf("-") < 0){
format = new SimpleDateFormat("yyyy");
}else{
format = new SimpleDateFormat("dd-MMM-yyyy");
}
try {
date = (Date)format.parse(s);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
Is there the possibility in have another format in the String s ? Or just these two?
public Date stringToDateReport(String strDate){
DateFormat formatnew SimpleDateFormat("dd-MM-yyyy");
Date date = null;
if(strDate.length()==4) {
format = new SimpleDateFormat("yyyy");
}
try {
date = (Date)format.parse(strDate);
} catch (ParseException e) {
//error parsing date
e.printStackTrace();
}
return date;
}
then call it like this :
String strDate = yourJson.getString("date");
Date d = stringToDateReport(strDate);

How to convert String of datetime to date using GWT?

In mysql, i have a field time_entered of type datetime (sample data: 2012-06-20 16:00:47). I also have a method, getTimeEntered(), that returns the value as String. I want to display the date in this format 2012-06-20 using DateTimeFormat from GWT.
here's my code:
String date = aprHeaderDW.getTimeEntered();
DateTimeFormat fmt = DateTimeFormat.getFormat("MM-dd-yyyy");
dateEntered.setText("" + fmt.format(date));
The problem is, the format method doesn't accept arguments as String. So if there's only a way I could convert the date from String to Date type, it could probably work. I tried typecasting but didn't work.
You should be able to just use DateTimeFormat.
Date date = DateTimeFormat.getFormat("yyyy-MM-dd HH:mm:ss").parse("2012-06-20 16:00:47");
String dateString = DateTimeFormat.getFormat("yyyy-MM-dd").format(date);
Otherwise there is a light-weight version of SimpleDateFormat that supports this pattern.
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2012-06-20 16:00:47");
Hi There are two options.
The first is as it is already a string you could use a regular expression to modify the format.
The second is using a SimpleDateFormater you can parse the string to a date then back again.
For example:
public class DateMerge {
public static void main(String arg[])
{
String out = dateConvert("2012-06-20 16:00:47");
System.out.println(out);
}
public static String dateConvert (String inDate)
{
try {
DateFormat formatter ;
Date date ;
formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
date = (Date)formatter.parse(inDate);
formatter = new SimpleDateFormat("dd-MM-yyyy");
String outDate = formatter.format(date);
return outDate;
} catch (ParseException e)
{System.out.println("Exception :"+e); }
return null;
}
}
You may use like this.
String date = "2012-06-20 16:00:47";
SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd");
String lDate=sf.format(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date));
System.out.println(lDate);
Output:
2012-06-20
After trying a lot of times I came up with a solution, based on #Keppil and adding my own code.
Here's Keppil's suggested solution for converting String datetime into Date type:
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2012-06-20 16:00:47");
...but my second requirement is to display just the date like 2012-06-20. Even though I removed HH:mm:ss, it still displayed the time like this 2012-06-20 00:00:00.
Here's my final solution:
Date date = null;
String d = rs.getString(SQL_CREATION_TIME); // assigns datetime value from mysql
// parse String datetime to Date
try {
date = new SimpleDateFormat("yyyy-MM-dd").parse(d);
System.out.println("time entered: "+ date);
} catch (ParseException e) { e.printStackTrace(); }
// format the Date object then assigns to String
Format formatter;
formatter = new SimpleDateFormat("yyyy-MM-dd");
String s = formatter.format(date);

Categories