Convert time to 24 hours format - java

I have some time value which is in String format (for example 12:45 AM and 7:00 PM).
I wonder how should I convert it into the 24 hours format (for example 12:45 and 19:00).
Should the output be in long format?

Please take a look at this page.
It has examples how to convert it back and forth.
Here is the 12hrs to 24hrs conversion.
import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.util.Date;
import java.text.ParseException;
String input = "2014-12-20 10:22:12 PM";
//Format of the date defined in the input String
DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss aa");
//Desired format: 24 hour format: Change the pattern as per the need
DateFormat outputformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
String output = null;
try{
//Converting the input String to Date
date= df.parse(input);
//Changing the format of date and storing it in String
output = outputformat.format(date);
//Displaying the date
System.out.println(output);
} catch (ParseException pe) {
pe.printStackTrace();
}

String dateStr = "12:45 AM";
DateFormat inputFormat = new SimpleDateFormat( "hh:mm aa" );
DateFormat outputFormat = new SimpleDateFormat( "HH:mm" );
Date date = null;
try{
date = inputFormat.parse( dateStr );
}
catch ( ParseException e ){
e.printStackTrace();
}
if( date != null ){
String formattedDate = outputFormat.format( date );
}

I'm not sure whether I get your question right, but shouldn't the following work?
Date date=new Date("01/01/14 " + myTimeString); // Example: 8:22:09 PM
System.out.println("Formattet ="+new SimpleDateFormat("HH:mm").format(date));

Related

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

How to convert java.util.Date to GMT format

I have a string "2014-07-02T17:12:36.488-01:00" which shows the Mountain time zone. I parsed this into java.util.date format. Now I need to convert this to GMT format. Can anyone help me??
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Object dd = null;
try {
dd=sdf.parseObject("2014-07-02T17:12:36.488-01:00");
System.out.println(dd);
} catch (ParseException e) {
e.printStackTrace();`enter code here`
}
SimpleDateFormat gmtDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
gmtDateFormat.setTimeZone(java.util.TimeZone.getTimeZone("GMT"));
System.out.println("Current Date and Time in GMT time zone:+ gmtDateFormat.format(dd));
There are a few problems in your code. For example, the format string doesn't match the actual format of the string you are parsing.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");
Object dd = null;
try {
dd = sdf.parse("2014-07-02T17:12:36.488-01:00");
System.out.println(dd);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat gmtDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssX");
gmtDateFormat.setTimeZone(java.util.TimeZone.getTimeZone("GMT"));
System.out.println("Current Date and Time in GMT time zone:" + gmtDateFormat.format(dd));
To print the current date in whatever timezone you like, set the timezone you want to use on the SimpleDateFormat object. For example:
// Create a Date object set to the current date and time
Date now = new Date();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");
df.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println("Current date and time in GMT: " + df.format(now));
df.setTimeZone(TimeZone.getTimeZone("IST"));
System.out.println("Current date and time in IST: " + df.format(now));

Formatting a date String

I have a string like this:
"2013-06-25 10:00:09"
I want to format it like this:
"25/06/2013 10:00".
I'm trying this:
SimpleDateFormat sdf = new SimpleDateFormat(""dd/MM/yyyy kk:mm"")
Date d;
try {
d = sdf.parse(data_publicao_db[totalCount_ + i]);
String s2 = (new SimpleDateFormat("yyyyMMdd")).format(d);
Log.d("Data test", "" + s2);
}
catch (ParseException e) { e.printStackTrace(); }
But it keeps giving a
ParseException: Unparseable date
Is there a better and right way to this?
sdf should be
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
the other SimpleDateFormat you need to reformat your date:
new SimpleDateFormat("dd/MM/yyyy HH:mm")
Let's go!
//your date String and SDF in your String format
String originalDateString = "2013-06-25 10:00:09";
SimpleDateFormat originalSdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//get the Date from the String
Date date = originalSdf.parse(originalDateString);
//Wanted output format
SimpleDateFormat wantedSdf= new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
//print it
System.out.println(wantedSdf.format(date));
Since data_publicao_db[totalCount_ + i] is looking like 2013-06-25 10:00:09, you have to parse it with a format of yyyy-MM-dd HH:mm:ss .
To convert the result to the format 25/06/2013 10:00, you have to format it with a SimpleDateFormat using the format dd/MM/yyyy HH:mm.

String Date Value Converting

I am converting String to Date format. But it returns "Unparseable date". for example,
String date= "Wednesday, May 15, 2013";
I want to convert this to String like "2013-05-15" How to do that?
Use SimpleDateFormat twice: Once to parse a Date, the other to render it in the desired format:
Date date;
String display = new SimpleDateFormat("yyyy-MM-dd").format(
new SimpleDateFormat("EEEE, MMMM dd, yyyy").parse(date)
);
Your example date is unfortunate, because it uses the only 3-letter month "May", so I can't tell if your month names are all truncated to 3 letters, or if they are the full name. I have assumed months to be the full name, but if they are truncated, change MMMM to MMM in the second format string.
Something like this might help (parse the date string to date object and format it back in the new format):
String dateString = "Wednesday, May 15, 2013";
DateFormat format1 = new SimpleDateFormat("EEEE, MMMM dd, yyyy");
Date date = format1.parse(dateString);
DateFormat format2 = new SimpleDateFormat("yyyy-MM-dd");
String updatedDateString = format2.format(date);
System.out.println("Updated Date > "+updatedDateString);
In my experiments with this, you need to do something like the below...Refer to the API for understanding how to construct your format strings. http://docs.oracle.com/javase/6/docs/api/index.html?java/text/DateFormat.html
String myDateAsString = "Wednesday, May 15, 2013";
SimpleDateFormat df = new SimpleDateFormat("EEEE, MMM d, yyyy");
Date d = new Date();
try {
d = df.parse(myDateAsString);
} catch (ParseException e1) {
System.out.println("Could not parse...something wrong....");
e1.printStackTrace();
}
df.applyPattern("yyyy-MM-d");
String convertedDate = df.format(d);
System.out.println(convertedDate);
This will be a good approach.
Something like this:
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class StringDate {
public static void main(String[] args) throws ParseException{
String dateString = "Wednesday, May 15, 2013";
DateFormat format1 = new SimpleDateFormat("E, MMM dd, yyyy");
Date date = format1.parse(dateString);
DateFormat format2 = new SimpleDateFormat("yyyy-MM-dd");
String updatedDateString = format2.format(date);
System.out.println("Updated Date > "+updatedDateString);
}
}

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