Reputation: 62596
I would like to have two functions:
Say I have the date in a string "11/12/2011"
and time in a String: "0200"
. I would like a simple function (if possible) that takes two parameters (the date and time from above) in java that converts it into 11/12/2011 2:00AM in a Java Date
object.
Say I have a java Date
object as the only parameter (e.g. 11/12/2011 2:00AM) that returns the military time from it, (e.g. "0200").
Is there some java library or what is the best way to accomplish the above? Or is there something built into java Date that makes it easy to get something in military time to normal time Java date uses?
Upvotes: 3
Views: 6247
Reputation: 338326
LocalDateTime ldt = LocalDateTime.of(
LocalDate.parse(
"11/12/2011" ,
DateTimeFormatter.ofPattern( "mm/DD/uuuu" )
)
,
LocalTime.parse(
"0200" ,
DateTimeFormatter.ofPattern( "HHmm" )
)
)
No such thing as "normal time" and "military time". Most people on the planet are fluent in both 12-hour clock time for casual use and 24-hour clock time for important matters such as train schedule. The term "military time" is mostly used in the United States where oddly few people outside the military know 24-hour time.
Avoid the troublesome old date-time classes such as java.util.Date
and .Calendar
. Now supplanted by the java.time classes.
You have a date-only value and a time-of-day value, and you want to combine them. So first establish each part.
The LocalDate
class represents a date-only value without time-of-day and without time zone. Similarly, the LocalTime
class represents a time-of-day without a date and without a time zone.
LocalDate
You can specify an explicit formatting pattern.
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern( "mm/DD/uuuu" ).withLocale( Locale.US );
LocalDate ld = LocalDate.parse( "11/12/2011" , dateFormatter );
ld.toString(): 2011-01-12
LocalTime
And do the same for time-of-day.
DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern( "HHmm" );
LocalTime lt = LocalTime.parse( "0200" , timeFormatter );
lt.toString(): 02:00
LocalDateTime
Join these two parts into a LocalDateTime
.
LocalDateTime ldt = LocalDateTime.of( ld , lt );
This LocalDateTime
does not represent an actual moment, a point on the timeline. This object has no real meaning without the context of an offset-from-UTC or a time zone. The moment of 2 AM in Auckland NZ is hours earlier than 2 AM in Kolkata IN which is hours earlier than 2 AM in Paris FR and still later is 2 AM in Montréal Québec CA.
From the LocalDateTime
you can extract a LocalDate
or LocalTime
when you again want a date-only or time-of-day-only value as requested in the Question.
LocalDate ld = ldt.toLocalDate();
LocalTime lt = ldt.toLocalTime();
ZonedDateTime
If you know the offset-from-UTC intended for this value, apply a ZoneOffset
to get an OffsetDateTime
. Even better, use a time zone if known, a ZonedId
to get a ZonedDateTime
.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ldt.atZone( z );
zdt.toString(): 2011-01-12T02:00:00-05:00[America/Montreal]
From the ZonedDateTime
you can extract a LocalDate
or LocalTime
when you again want a date-only or time-of-day-only value as requested in the Question.
LocalDate ld = zdt.toLocalDate();
LocalTime lt = zdt.toLocalTime();
Best to avoid java.util.Date
like the Plague. But if you must to work with old code not yet updated to java.time types, you can convert to/from java.time by calling new methods added to the old classes. From a ZonedDateTime
you can extract an java.time.Instant
(a moment on the timeline in UTC) and feed that to a static method on Date
.
java.util.Date utilDate = java.util.Date.from( zdt.toInstant() );
For more conversion info, see Convert java.util.Date to what “java.time” type?.
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as java.util.Date
, .Calendar
, & java.text.SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
Upvotes: 0
Reputation: 325
That's how I did.
Here is my code:
import java.util.Scanner;
class test{
int h,m,s;
public static void main (String args[]){
int hour,min,sec;
String format;
Scanner obj=new Scanner(System.in);
hour=obj.nextInt();
min=obj.nextInt();
sec=obj.nextInt();
format=obj.next();
int h,m,s;
h=((hour>=00&&hour<24)?hour:0);
m=((min>=00&&min<60)?min:0);
s=((sec>=00&&sec<60)?sec:0);
if(format.equals("PM")){
h= (h!=12? 12+h :h);
}else if (h==12)h=0;
System.out.print(h+":"+m+":"+s);
}}
Upvotes: 0
Reputation: 1
Thats how I did it
public static String militaryToOrdinaryTime(int milTime)
{
int hour = milTime / 100;
int min = milTime % 100;
String period;
if (hour < 0 || hour > 24 || min < 0 || min > 59)
{
return "";
}
else if (hour > 12)
{
hour = hour - 12;
period = "pm";
}
else
{
period = "am";
}
if (hour == 0)
{
hour = 12;
}
else if (min == 0)
{
String ordTime = hour + " " + period;
return ordTime;
}
else if (min < 10 && min > 0)
{
String min1 = String.valueOf(min);
min1 = "0" + min1;
String ordTime = hour + ":" + min1 + " " + period;
return ordTime;
}
String ordTime = hour + ":" + min + " " + period;
return ordTime;
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int time = in.nextInt();
System.out.println(militaryToOrdinaryTime(time));
}
}
Upvotes: 0
Reputation: 46872
new SimpleDateFormat("MM/dd/yyyy HHmm").parse("11/12/2011" + " " + "0200");
new SimpleDateFormat("MM/dd/yyyy HHmm").format(new Date());
new SimpleDateFormat("HHmm").format(new Date());
(assuming the military in the US still put month first in dates).
[edit: you need to worry about your time zone too - for parsing it's often easiest to simply append this. for example:
new SimpleDateFormat("MM/dd/yyyy HHmm Z").parse("11/12/2011" + " " + "0200" + " PST");
(maybe the military always use UTC? i have no idea...). and for formatting, you can set the timezone on the SDF instance using setTimezone().]
Upvotes: 3
Reputation: 6182
You can use SimpleDateFormat.parse with the appropriate format string.
Upvotes: 1