I want to convert 24 Hour time into 12 Hour AM/PM time.
e.g:- How to convert date 2012-03-20T22:30:00.000+05:30 to to 2012-03-20 10:30 PM??
I have extratced the date but its in 24 Hour time. I though used SimpleDateFormater but still for 12.30 it is showing 00.30 and not 12.30 PM.
Thanks in advance.
Try this:
String dateStr = new SimpleDateFormat("yyyy-MM-dd hh:mm a").format(new Date());
The bundled java.util.Date and .Calendar classes are notoriously troublesome. Avoid them. Use either Joda-Time or the new java.time package in Java 8.
Joda-Time
DateTimeZone timeZone = DateTimeZone.ForID( "Asia/Kolkata" );
DateTime dateTime = new DateTime( "2012-03-20T22:30:00.000+05:30", timeZone );
Java.util.Locale locale = java.util.Locale.Builder().setLanguage("en").setRegion("IN").build();
DateTimeFormatter formatter = DateTimeFormat.forStyle( "SS" ).withLocale( locale).withZone( timeZone );
String output = formatter.print( dateTime );
Related
I have a requirement where i have to store different date and time with time zones.
I have used ZonedDateTime of java 8 .
ZoneId zoneId = ZoneId.of("US/Eastern");
ZonedDateTime zt = ZonedDateTime.now(zoneId);
System.out.println(zt.toString());
My problem is I want to store this in java.util.Date format.
I used DateTimeFormatter
DateTimeFormatter dtf=DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ");
dtf.format(zt);
Until here it works fine this gives me the required date in string format now when i try to convert this to java.util.Date using simple date format
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
System.out.println(sdf.parse(dtf.format(zt)));
I get output as Sat Mar 12 00:44:10 IST 2016 but i want output as 2016-03-11T14:14:10-05:00 in java.util.Date type. Can somebody suggest where am i going wrong?
You are using a wrong way this is the corrected code
sdf.format(sdf.parse(val)) this the right way.
ZoneId zoneId = ZoneId.of("US/Eastern");
ZonedDateTime zt = ZonedDateTime.now(zoneId);
System.out.println(zt.toString());
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ");
String val = dtf.format(zt);
System.out.println(val);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
//String dateStr = zt.format(sdf);
System.out.println(sdf.format(sdf.parse(val)));
ZonedDateTime > Instant > Date
Best to avoid the old date-time classes including java.util.Date. But if you must, you can convert. Call the new from method on the old java.util.Date class.
For that you need an Instant a moment on the timeline in UTC.
Instant instant = myZonedDateTime.toInstant();
java.util.Date juDate = java.util.Date.from( instant );
To go the other direction:
Instant instant = juDate.toInstant();
I have the following string "2015-04-02 11:52:00+02" and I need to parse it in Java to a Timestamp.
I tried all sorts of formats including
SimpleDateFormat mdyFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss+Z");
but nothing seems to work - I keep getting a ParseException
Can anyone help?
I need something like:
SimpleDateFormat mdyFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss+Z");
Timestamp t = new Timestamp(mdyFormat.parse("2015-04-02 11:52:00+02").getTime());
Try This
String str="2009-12-31 23:59:59 +0100";
/\
||
Provide Space while providing timeZone
SimpleDateFormat mdyFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");
System.out.println(mdyFormat.parse(str));
Output
Fri Jan 01 04:29:59 IST 2010
java.sql.Timestamp objects don't have time zones - they are instants in time, like java.util.Date
So try this:
SimpleDateFormat mdyFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Timestamp t = new Timestamp(mdyFormat.parse("2015-04-02 11:52:00").getTime());
try "yyyy-MM-dd HH:mm:ssX"
Z stand for timezone in the following format: +0800
X stand for timezone in the following format: +08
Examples here
ISO 8601
Replace that SPACE in the middle with a T and you have a valid standard (ISO 8601) string format that can be parsed directly by either the Joda-Time library or the new java.time package built into Java 8 (inspired by Joda-Time). Search StackOverflow for hundreds of examples.
If using java.time, read my comment on Question about a bug when parsing hours-only offset value.
Example in Joda-Time 2.7.
String inputRaw = "2015-04-02 11:52:00+02";
String input = inputRaw.replace( " ", "T" );
DateTimeZone zone = DateTimeZone.forID( "America/Montreal" ); // Specify desired time zone adjustment.
DateTime dateTime = new DateTime( input, zone );
my timezone is GMT+1.
so a "Date"-object with "22.09.1985 00:00UTC" prints "Sun Sep 22 01:00:00 CEST 1985" on the tostring function.
Now i'm trying to create this date by parsing "22/09/1985" with simpleDateFormat
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
sdf.setTimeZone(TimeZone.getDefault());
Date d = sdf.parse("22/09/1985");
=> Sun Sep 22 00:00:00 CEST 1985
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date d = sdf.parse("22/09/1985");
=> Sun Sep 22 02:00:00 CEST 1985
how can i configure simpledateformat that it creates an Date which prints "Sun Sep 22 01:00:00 CEST 1985" with input string "22/09/1985"?
My assumption was wrong,
22.09.1985 00:00UTC is actually 22.09.1985 02:00CET
so
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date d = sdf.parse("22/09/1985");
is exactly what i wanted, the date i compared it with was wrong.
Avoid java.util.Date & Calendar
You’ve found one of the many reasons to avoid using java.util.Date & .Calendar. They are notoriously troublesome. Either use Joda-Time or, in Java 8, the new java.time package which is inspired by Joda-Time and defined by JSR 310.
Search StackOverflow for "joda date" to find many examples.
Time Zone
You said:
my timezone is GMT+1.
Incorrect, your local offset from UTC/GMT is +01. That is not your time zone. A time zone is an offset plus rules about Daylight Saving Time (DST) and other anomalies.
And that offset should have two digits: +01 (or +01:00) rather than +1, according to the ISO 8601 standard.
Avoid the 3 or 4 letter codes such as CET. They are neither standardized nor unique. Use proper time zone names.
Generally speaking, you should specify a time zone in all your date-time work rather than rely on the current JVM's default.
In both Joda-Time and java.time, a date-time object truly knows its assigned time zone. A java.util.Date has no time zone, but seems to because its toString applies the default time zone when creating a String representation, as you sadly learned the hard way.
Example Code
Some code using Joda-Time 2.3.
String input = "22/09/1985";
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Amsterdam" );
DateTimeFormatter formatter = DateTimeFormat.forPattern( "dd/MM/yyyy" );
DateTime dateTime = formatter.withZone( timeZone ).parseDateTime( input );
DateTime dateTimeUtcGmt = dateTime.withZone( DateTimeZone.UTC );
DateTime dateTimeIndia = dateTime.withZone( DateTimeZone.forID( "Asia/Kolkata" ) );
String outputMontreal = DateTimeFormat.forStyle( "FF" ).withZone( DateTimeZone.forID( "America/Montreal" ) ).withLocale( Locale.CANADA_FRENCH ).print( dateTime );
// All of the above date-time represent the very same moment in the timeline of the Universe.
Dump to console…
System.out.println( "dateTime: " + dateTime );
System.out.println( "dateTimeUtcGmt: " + dateTimeUtcGmt );
System.out.println( "dateTimeIndia: " + dateTimeIndia );
System.out.println( "outputMontreal: " + outputMontreal );
When run…
dateTime: 1985-09-22T00:00:00.000+02:00
dateTimeUtcGmt: 1985-09-21T22:00:00.000Z
dateTimeIndia: 1985-09-22T03:30:00.000+05:30
outputMontreal: samedi 21 septembre 1985 18 h 00 EDT
The fact that you're parsing a date string, using a specific time zone, doesn't make the printed Date object to use that time zone. You're still using the same implementation of Date#toString(), which formats the Date object using the default timezone.
What you would need is to format your Date object with that SimpleDateFormat object. And if you have that specific string, then you would need another SimpleDateFormat object for parsing that string:
String dateString = "22/09/1985";
SimpleDateFormat parser = new SimpleDateFormat("dd/MM/yyyy");
Date parsedDate = parser.parse(dateString);
SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(formatter.format(parsedDate));
Java Date doesn't have the concept of TimeZone associated with it. You can only format a Date object using a specified timezone, and get a string. Or else, switch to JodaTime library.
Date is a relatively "dumb" class, as it just represents the number of milliseconds since 1970-01-01 00:00:00 UTC.
If you want to print out a Date as if it were a different timezone, you need to construct a DateFormat / SimpleDateFormat for that TimeZone and format it to a String that way.
SimpleDateFormat parser = new SimpleDateFormat("HH:mm");
Date time1 = parser.parse("7:30");
Now if I want to add 2 more hours to time1, like:
7:30 + 2 = 9:30
how do I add the 2 hours?
java.util.Date is deprecated, you should use java.util.Calendar instead.
SimpleDateFormat parser = new SimpleDateFormat("HH:mm");
Date myDate = parser.parse("7:30");
Calendar cal =Calendar.getInstance();
cal.setTime(myDate);
cal.add(Calendar.HOUR_OF_DAY,2); // this will add two hours
myDate = cal.getTime();
And even better solution is to use Joda Time - Java date and time API.
From their website - Joda-Time provides a quality replacement for the Java date and time classes.
Convert java.util.Date into java.util.Calendar Object and use Calendar.add() method to add Hours
SimpleDateFormat parser = new SimpleDateFormat("HH:mm");
Date time1 = parser.parse("7:30");
Calendar cal =Calendar.getInstance();
cal.setTime(time1);
cal.add(Calendar.Hour_Of_Day, 2);
time1 =cal.getTime();
System.out.println(parser.format(time1));//returns 09:30
tl;dr
LocalTime.parse( "07:30" ).plusHours( 2 )
…or…
ZonedDateTime.now( ZoneId.of( " Pacific/Auckland" ) )
.plusHours( 2 )
java.time
The old date-time classes such as java.util.Date, .Calendar, and java.text.SimpleDateFormat should be avoided, now supplanted by the java.time classes.
LocalTime
For a time-of-day only value, use the LocalTime class.
LocalTime lt = LocalTime.parse( "07:30" );
LocalTime ltLater = lt.plusHours( 2 );
String output = ltLater.toString(); // 09:30
Instant
For a given java.util.Date, convert to java.time using new methods added to the old classes. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds.
Instant instant = myUtilDate.toInstant();
Or capture current moment in UTC as an Instant.
Instant instant = Instant.now();
Add two hours as seconds. The TimeUnit class can convert hours to seconds.
long seconds = TimeUnit.HOURS.toSeconds( 2 );
Instant instantLater = instant.plusSeconds( seconds );
ZonedDateTime
To view in the wall-clock time of some community, apply a time zone. Apply a ZoneId to get a ZonedDateTime object.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );
You can add hours. The ZonedDateTime class handles anomalies such as Daylight Saving Time.
ZonedDateTime zdtLater = zdt.plusHours( 2 );
Duration
You can represent that two hours as an object.
Duration d = Duration.ofHours( 2 ) ;
ZonedDateTime zdtLater = zdt.plus( d ) ;
Calendar cal = Calendar.getInstance();
cal.setTimeZone(TimeZone.getTimeZone("PST"));
cal.setTime(new Date());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a");
Date resultdate = new Date(cal.getTimeInMillis());
sdf.setTimeZone(TimeZone.getTimeZone("PST"));
System.out.println("String date:"+sdf.format(resultdate));
System.out.println("Date:"+sdf.parse(sdf.format(resultdate)));
output:
String date:2011-12-29 09:01:58 PM
Date:Fri Dec 30 10:31:58 IST 2011
Problem:
sdf.format(resultdate) returning correct date and time to as per timezone. But,
sdf.parse(sdf.format(resultdate)) not returning correct date and time to as per timezone, how to fix this problem?
The Date class is merely a thin wrapper around the number of milli-seconds past the 'epoch' (January 1, 1970, 00:00:00 GMT). It doesn't store any timezone information. In your last call you are adding a date instance to a String which implicitly calls the toString() method. The toString() method will use the default timezone to create a String representing the instance (as it doesn't store any timezone info). Try modifying the last line to avoid using the toString() method.
System.out.println("Date:" + sdf.format(sdf.parse(sdf.format(resultdate))));
Try using joda-Time api for your convenience. Example is here
Unfortunatley Java date returns time in GMT only. When ever you want display in front end or some where, you need to use the formated String generated in your step1.
try the below code will, it will work.
Calendar cal = Calendar.getInstance();
cal.setTimeZone(TimeZone.getTimeZone("PST"));
cal.setTime(new Date());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a");
Date resultdate = new Date(cal.getTimeInMillis());
sdf.setTimeZone(TimeZone.getTimeZone("PST"));
System.out.println("String date:"+sdf.format(resultdate));
System.out.println("Date:"+sdf2.parse(sdf.format(resultdate)));
Three-Letter Time Zone Codes
Avoid using the three-letter time zone codes. They are neither standardized nor unique. For example, IST means both India Standard Time and Irish Standard Time. Furthermore, the codes are meant to distinguish Daylight Saving Time (DST) but that only confuses matters.
Use proper descriptive time zone names to retrieve a time zone object that encompasses DST and other issues.
Joda-Time
The java.util.Date & Calendar classes bundled with Java are notoriously troublesome. Avoid them. Use Joda-Time or the new java.time.* package bundled with Java 8.
In JodaTime, a DateTime object truly knows its own time zone (unlike java.util.Date). Usually we use the immutable classes in Joda-Time. So instead of changing the time zone in a DateTime object, we create a fresh new DateTime object based on the old but with a specified difference. A different time zone might be that difference.
Here is some example code.
DateTimeZone timeZone_India = DateTimeZone.forID( "Asia/Kolkata" );
DateTimeZone timeZone_Ireland = DateTimeZone.forID( "Europe/Dublin" );
DateTimeZone timeZone_US_West_Coast = DateTimeZone.forID( "America/Los_Angeles" );
DateTime now = new DateTime( timeZone_India );
System.out.println( "now in India: " + now );
System.out.println( "now in Ireland: " + now.withZone( timeZone_Ireland ) );
System.out.println( "now in US West Coast: " + now.withZone( timeZone_US_West_Coast ) );
System.out.println( "now in UTC/GMT: " + now.withZone( DateTimeZone.UTC ) );
When run…
now in India: 2014-02-10T13:52:27.875+05:30
now in Ireland: 2014-02-10T08:22:27.875Z
now in US West Coast: 2014-02-10T00:22:27.875-08:00
now in UTC/GMT: 2014-02-10T08:22:27.875Z
java.time
Same idea using the java.time classes which supplant Joda-Time.
The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = Instant.now();
Apply a time zone.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );
The instant and the zdt represent the same moment, the same point on the timeline. Each is seen through the lens of a different region’s wall-clock time.
Generate a String by either specifying a formatting pattern or by letting java.time automatically localize.
To localize, specify:
FormatStyle to determine how long or abbreviated should the string be.
Locale to determine (a) the human language for translation of name of day, name of month, and such, and (b) the cultural norms deciding issues of abbreviation, capitalization, punctuation, and such.
Example:
Locale l = Locale.CANADA_FRENCH ;
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL ).withLocale( l );
String output = zdt.format( f );