How to display only time part from date time combination in java - 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));
}

Related

Setting an Input with separate year, month and day

I've set an AlertDialog.builder in which there is an input, to obtain a date from the user. Currently, it's set like that:
input.setInputType(InputType.TYPE_CLASS_DATETIME | InputType.TYPE_DATETIME_VARIATION_NORMAL);
What I would like, isn't simply an entire line on which the user has to write. I would like a thing like
Input: __/__/____
Where the user would have to complete with
Input: 18/04/2018
And then I would get the whole thing as a string: "18-04-2018"
What can I do?
You can parse the string to LocalDate then format to desired format, or you can just replace / with -:
String input = "18/04/2018";
String outPut;
// first approach
LocalDate localDate = LocalDate.parse(input, DateTimeFormatter.ofPattern("dd/MM/yyyy"));
outPut = localDate.format(DateTimeFormatter.ofPattern("dd-MM-yyyy"));
// second approach
outPut = input.replaceAll("/", "-");
You have to use SimpleDateFormat which will change the format of date. have look this
public static String changeDateToTimeStamp(String date){
DateFormat inputFormat = new SimpleDateFormat("dd/mm/yyyy");
DateFormat outputFormat = new SimpleDateFormat("dd-mm-yyyy");
Date date1 = null;
try {
date1 = inputFormat.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
return outputFormat.format(date1);
}
this method will return date like "18-04-2018". Hope it will help you!

How to convert ISOdate in String in 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 "";
}

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;
}
}

How to convert string to date format

I want to convert 3/13/2014 11:38:58 AM string to date format.
I see some examples but and also implement but I don't know how to convert AM/PM to 24 hour time format.
How to make it possible ?
Use SimpleDateFormat
Date date = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a").parse(string);
Using this you can convert your date and time..
SimpleDateFormat formatter = new SimpleDateFormat("mm/dd/yyyy hh:mm:ss a");
Date date_current = new Date();
Date date_start = null;
date_start = sdf.parse("3/13/2014 11:38:58 AM");
System.out.println("now time is.." + date_start);
Thanks..
Parsing Strings into Dates:
The SimpleDateFormat class has some additional methods, notably parse( ) , which tries to parse a string according to the format stored in the given SimpleDateFormat object. For example:
import java.util.*;
import java.text.*;
public class DateDemo {
public static void main(String args[]) {
SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd");
String input = args.length == 0 ? "1818-11-11" : args[0];
System.out.print(input + " Parses as ");
Date t;
try {
t = ft.parse(input);
System.out.println(t);
} catch (ParseException e) {
System.out.println("Unparseable using " + ft);
}
}
}

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