Get Time stamp using Java GMT+5:30 - java

I want Timestamp of given date.
using this code
public static String getTimestamp(String time)
{
DateFormat dfm = new SimpleDateFormat("dd-mm-yy hh:mm:ss");
long unixtime = 0;
dfm.setTimeZone(TimeZone.getTimeZone("GMT+5:30"));
try
{
unixtime = dfm.parse(time).getTime();
unixtime=unixtime/1000;
}
catch (ParseException e)
{
e.printStackTrace();
}
return ""+unixtime;
}
public static void main(String[] args)
{
System.out.println(getTimestamp("11-05-15 11:54:55"));
}
but when i enter this date 11-05-15 11:54:55 then program return me 1420957495 this timestamp which is timestamp of Jan (01) but i want May(06)
please help me

use this
DateFormat dfm = new SimpleDateFormat("dd-MM-yy hh:mm:ss");
Upper case MM is for month and lower case is for minute

Your Offset Is Invalid
A valid offset must include padded zero. Your offset string GMT+5:30 should be GMT+05:30 with a 0 before the 5.
Beyond that, the Answer by Meno Hochschild is correct and wise.
java.time
The java.util.Date/.Calendar and SimpleDateFormat classes are notoriously troublesome, confusing, and flawed. Avoid them.
Instead use java.time package found in Java 8 and later. Where lacking, use the Joda-Time library.
Here is some java.time code (Java 8).
First, parse your input into a "local" date-time value, meaning without any time zone attached. As there was no offset nor time zone included with the input, this value could apply to any particular locality.
String input = "11-05-15 11:54:55"; // Strongly recommend using 4-digit year whenever possible, as suggested in Meno Hochschild’s Answer.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "dd-MM-yy HH:mm:ss" ); // No need for Locale in this case, but always consider it.
LocalDateTime localDateTime = LocalDateTime.parse( input , formatter );
Next, we are presuming this value was meant to represent a moment in India. Let’s assign a time zone. We could assign merely an offset. But generally we should use a time zone. A time zone is an offset plus the past, present, and future set of rules for adjustments and anomalies such as Daylight Saving Time.
First we instantiate a time zone for India. Then we generate a ZonedDateTime based on the LocalDateTime while adding a time zone.
// Assign a time zone.
//ZoneId zoneId_plus_5_30 = ZoneId.of( "GMT+05:30" ); // You can use an offset, but know that a time zone is *more* than an offset.
ZoneId zoneIdKolkata = ZoneId.of( "Asia/Kolkata" ); // Better to use a time zone name if one is applicable. Ex: "Asia/Kolkata".
ZonedDateTime zonedDateTimeKolkata = ZonedDateTime.of( localDateTime , zoneIdKolkata );
For fun, let’s adjust the same moment to UTC and to Montréal.
ZonedDateTime zonedDateTimeUtc = zonedDateTimeKolkata.withZoneSameInstant( ZoneOffset.UTC );
ZonedDateTime zonedDateTimeMontréal = zonedDateTimeKolkata.withZoneSameInstant( ZoneId.of( "America/Montreal" ) );
Dump to console.
System.out.println( "Input: " + input );
System.out.println( "localDateTime: " + localDateTime );
System.out.println( "zonedDateTimeKolkata: " + zonedDateTimeKolkata );
System.out.println( "zonedDateTimeUtc: " + zonedDateTimeUtc );
System.out.println( "zonedDateTimeMontréal: " + zonedDateTimeMontréal );
When run.
Input: 11-05-15 11:54:55
localDateTime: 2015-05-11T11:54:55
zonedDateTimeKolkata: 2015-05-11T11:54:55+05:30[Asia/Kolkata]
zonedDateTimeUtc: 2015-05-11T06:24:55Z
zonedDateTimeMontréal: 2015-05-11T02:24:55-04:00[America/Montreal]

You should change your pattern. So far the accepted answer is right with respect to month. What is still missing is the pattern symbol for the hour of day. It should be H instead of h. Or if you prefer the English hour notation, you can use an additional letter "a" indicating AM/PM. So the final solution is:
DateFormat dfm = new SimpleDateFormat("dd-MM-yy HH:mm:ss");
or
DateFormat dfm = new SimpleDateFormat("dd-MM-yy hh:mm:ss a", Locale.ENGLISH);
And I recommend to use 4-digit-years to exclude any ambivalence using yyyy, by the way.

Related

Issue with parsing date time using ZonedDateTime and DateTimeFormatter

I am having two different results from these two blocks even though the input date/time to parse is the same
public class DateTimeFormatterUtilsTest
{
private static final String ISO_DATETIME_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";;
private static final String ISO_DATETIME_TO_PARSE = "2007-12-03T10:15:30.000Z";
private static final long TARGET_EPOCH_TIME = 1196676930000L;
#Test
public void testDateTimeFormatterUtils()
{
ZoneId targetZoneid = TimeUtils.getZoneId(TIMEZONE.PST);
DateTimeFormatter formatter = DateTimeFormatter.ISO_INSTANT.withZone(targetZoneid);
long epochTime = parseDateTime(ISO_DATETIME_TO_PARSE, formatter);
assertTrue(epochTime == TARGET_EPOCH_TIME);
// specify custom pattern
DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern(ISO_DATETIME_PATTERN).withZone(targetZoneid);
epochTime = parseDateTime(ISO_DATETIME_TO_PARSE, formatter1);
assertTrue(epochTime == TARGET_EPOCH_TIME);
}
public long parseDateTime(final String dateTimeString, DateTimeFormatter formatter)
{
ZonedDateTime zonedDateTime = ZonedDateTime.parse(dateTimeString, formatter);
System.out.println("parsed zoned date time" + zonedDateTime);
Instant instant = zonedDateTime.toInstant();
long epochTime = instant.toEpochMilli();
System.out.println("Epoch time for" + ISO_DATETIME_TO_PARSE + "is " + epochTime);
return epochTime;
}
}
When I am using DateTimeFormatter.ISO_INSTANT I get the correct epoch time which is 1196676930000, however, when I am usin the .ofPattern method to create the DateTimeFormatter I am getting 1196705730000. Not sure why?
As you can see, the difference is 28 800 000 milliseconds or exactly 8 hours.
Never put quote marks around the Z in a date-time formatting pattern.
Z means +00:00
The Z is a standard abbreviation for an offset of zero. Pronounced “Zulu” per aviation/military convention.
Yuor quotes treat the Z as meaningless string literal, preventing semantic interpretation. The Z carries vital information, meaning “an offset from UTC of zero hours-minutes-seconds”. But your 'Z' parsing pattern ignores that info.
This:
"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
… should be:
"yyyy-MM-dd'T'HH:mm:ss.SSSZ"
By ignoring that offset, the JVM’s current default time zone is applied implicitly when you parsed as a ZonedDateTime. Hence your correct but unexpected results.
Instant, not ZonedDateTime
Your input has no indication of time zone. So ZonedDateTime is not called for here.
Instead, parse as an Instant.
Instant.parse( "2007-12-03T10:15:30.000Z" )
If you want to see that moment through the lens of a particular time zone, apply a ZoneId to get a ZonedDateTime. Same moment, different wall-clock time.
ZoneId z = ZoneId.of( "America/New_York" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
Terminology
Quick review of terms:
UTC is the temporal prime meridian. In the old days this was the time kept at the Royal Observatory in Greenwich, London.
An offset is merely a number of hours-minutes-seconds ahead or behind UTC.
A time zone is a named history of the past, present, and future changes to the offset used by the people of a particular region as decided by their politicians.

Compare ZoneDateTime with different time zones

Hi I've already search for similar questions but without luck.
I'm calling a ws that sends me back a token and when it's valid example:
{
"token": ...,
"notBefore":"Thu 21 Jul 2022 at 10:50:43",
"notOnOrAfter":"Thu 21 Jul 2022 at 12:50:43"
}
I know that this dates are GMT+2 (Rome), now I'm taking the current time and convert the two strings:
ZonedDateTime currentTime = LocalDateTime.now().atZone(ZoneId.of("GMT+2"));
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(token.getTimePattern(), Locale.ENGLISH);
ZonedDateTime tokenNotValidAfter = LocalDateTime.parse(token.getNotOnOrAfter(), dateTimeFormatter).atZone(ZoneId.of("GMT+2"));
ZonedDateTime tokenNotValidBefore = LocalDateTime.parse(token.getNotBefore(), dateTimeFormatter).atZone(ZoneId.of("GMT+2"));
if (!currentTime.isAfter(tokenNotValidBefore) || !currentTime.isBefore(tokenNotValidAfter)) {
throw new CifTokenExpiredException(ExceptionHandlerConfig.CIF_TOKEN_EXPIRED);
}
Now locally everthing is working fine, when i deploy on cloud i get:
ZonedDateTime currentTime = LocalDateTime.now().atZone(ZoneId.of("GMT+2"));
two hours behind.
How can i solve this without adding two hours to currentTime? (doing like this locally will not work)
Regards
GMT+2 is an offset, Middle Europe +1 hour plus 1 hour summer time.
That would go wrong in the coming winter. In fact you are using the incomplete OffsetDateTime, which without Locale is inconclusive for the real Zone.
ZonedDateTime currentTime = ZonedDateTime.now(ZoneId.of("Europe/Rome"));
As you see, no need to revert to LocalDateTime.
Now you can get currentTime.toInstant() for an absolute UTC number.
An Instant is even Comparable, but Before/After is fine.
You assume that before and after limits are also in the Italian time zone, but that may be as it is.
There are some things to consider, because of DST (summer time, daylight savings time):
With a count down ("Still 243 hours till the end") you can get awkward jumps of 1 hour per day.
Twice a year there is the 02:00-03:00 gap or repetition (Western Europe). These stati can be queried.
The answer by Joop Eggen is correct. I'll add some more complete code example.
I suggest you educate the publisher of your data on two points:
Date-time values being exchanged textually should use standard ISO 8601 format rather than inventing a localized format as seen in your case.
Moments (specific points on the timeline) should always be communicated in the context of a time zone or offset. Preferably with an offset of zero hours-minutes-seconds. This implied time zone of Rome is just asking for trouble. Or, if not a moment but a time-of-day that should remain the same even if politicians change the time zone rules, then communicate the intended time zone as another field in the date stream, in Continent/Region format such as Europe/Rome.
I suggest adding the ThreeTen-Extra library to your project. Doing so gives you the Interval class that represents a span of time attached to the timeline as a pair of Instant objects. Handy methods include contains, abuts, overlaps, and more.
String inputBegin = "Thu 21 Jul 2022 at 10:50:43";
String inputEnd = "Thu 21 Jul 2022 at 12:50:43";
Locale locale = Locale.US;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "EEE d MMM uuuu 'at' HH:mm:ss" ).withLocale( locale );
ZoneId zoneId = ZoneId.of( "Europe/Rome" ); // Assumed to be the intended time zone.
LocalDateTime beginLdt = LocalDateTime.parse( inputBegin , f );
LocalDateTime endLdt = LocalDateTime.parse( inputEnd , f );
ZonedDateTime begin = beginLdt.atZone( zoneId );
ZonedDateTime end = endLdt.atZone( zoneId );
Interval whenValid = Interval.of( begin.toInstant() , end.toInstant() );
Instant now = Instant.now();
boolean isValidNow = whenValid.contains( now );
System.out.println( begin + "/" + end );
String message = "Interval: " + whenValid + " contains now: " + now + " = " + isValidNow;
System.out.println( message );
2022-07-21T10:50:43+02:00[Europe/Rome]/2022-07-21T12:50:43+02:00[Europe/Rome]
Interval: 2022-07-21T08:50:43Z/2022-07-21T10:50:43Z contains now: 2022-07-21T21:17:54.458095Z = false
In the cloud time is always considered to be GMT. So the best action is to change ZonedDateTime currentTime = LocalDateTime.now().atZone(ZoneId.of("GMT+2"));
to
ZonedDateTime currentTime = ZonedDateTime.now()

Plus 1 hour and 1 day in date using java 8 apis

I have this code to add 1 hour or 1 day in date Java 8, but doesn´t work
String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
java.text.SimpleDateFormat format = new java.text.SimpleDateFormat(DATE_FORMAT);
Date parse = format.parse("2017-01-01 13:00:00");
LocalDateTime ldt = LocalDateTime.ofInstant(parse.toInstant(), ZoneId.systemDefault());
ldt.plusHours(1);
ZonedDateTime zdt = ldt.atZone(ZoneId.systemDefault());
Date te = Date.from(zdt.toInstant());
What´s wrong? The code shows: Sun Jan 01 13:00:00 BRST 2017
LocalDateTime is immutable and returns a new LocalDateTime when you call methods on it.
So you must call
ldt = ldt.plusHours(1);
Apart from the issue that you don't use the result of your date manipulation (ldt = ldt.plusHours(1)), you don't really need to go via a LocalDateTime for this operation.
I would simply use an OffsetDateTime since you don't care about time zones:
OffsetDateTime odt = parse.toInstant().atOffset(ZoneOffset.UTC);
odt = odt.plusDays(1).plusHours(1);
Date te = Date.from(odt.toInstant());
You could even stick to using Instants:
Instant input = parse.toInstant();
Date te = Date.from(input.plus(1, DAYS).plus(1, HOURS));
(with an import static java.time.temporal.ChronoUnit.*;)
tl;dr
LocalDateTime.parse( // Parse input string that lacks any indication of offset-from-UTC or time zone.
"2017-01-01 13:00:00".replace( " " , "T" ) // Convert to ISO 8601 standard format.
).atZone( // Assign a time zone to render a meaningful ZonedDateTime object, an actual point on the timeline.
ZoneId.systemDefault() // The Question uses default time zone. Beware that default can change at any moment during runtime. Better to specify an expected/desired time zone generally.
).plus(
Duration.ofDays( 1L ).plusHours( 1L ) // Add a span of time.
)
Details
Do not mix the troublesome old legacy classes Date and Calendar with the modern java.time classes. Use only java.time, avoiding the legacy classes.
The java.time classes use the ISO 8601 standard formats by default when parsing and generating strings. Convert your input string by replacing the SPACE in the middle with a T.
String input = "2017-01-01 13:00:00".replace( " " , "T" ) ;
LocalDateTime ldt = LocalDateTime.parse( input ) ;
ALocalDateTime does not represent an actual moment, not a point on the timeline. It has no real meaning until you assign a time zone.
ZoneId z = ZoneId.systemDefault() ; // I recommend specifying the desired/expected zone rather than relying on current default.
ZonedDateTime zdt = ldt.atZone( z ) ;
A Duration represents a span of time not attached to the timeline.
Duration d = Duration.ofDays( 1L ).plusHours( 1L ) ;
ZonedDateTime zdtLater = zdt.plus( d ) ;

Not able to convert EST to IST time in Java

Hi i am currently work on creating Desktop application using Swing.I was able to convert IST to EST time using Date class in java but not able to convert EST to IST time and it gives same EST time as IST time. Please find the below code .
ChangetoEST function is giving correct EST time from IST time.
ChangetoIST function is not giving correct IST time from EST time and showing given EST time as IST time.
public String changetoEST(String date) throws ParseException
{
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy hh:mm a");
String dateInString = date;
Date d=formatter.parse(dateInString);
TimeZone tzInAmerica = TimeZone.getTimeZone("America/New_York");
formatter.setTimeZone(tzInAmerica);
String sDateInAmerica = formatter.format(d);
Date dateInAmerica = formatter.parse(sDateInAmerica);
String a=formatter.format(dateInAmerica);
return a;
}
public String changetoIST(String date) throws ParseException
{
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy hh:mm a");
String dateInString = date;
Date d=formatter.parse(dateInString);
TimeZone tzInIndian = TimeZone.getTimeZone("Asia/Calcutta");
formatter.setTimeZone(tzInIndian);
String sDateInAmerica = formatter.format(d);
Date dateInAmerica = formatter.parse(sDateInAmerica);
String a=formatter.format(dateInAmerica);
return a;
}
The parse calls are done without you explicitly setting a time zone, which means that parsing is done using your default time zone.
Set the source time zone before parsing, parse, set time zone to target time zone, and format result.
E.g.
public static String istToEst(String dateInput) throws ParseException {
return changeTimeZone(dateInput, TimeZone.getTimeZone("Asia/Calcutta"),
TimeZone.getTimeZone("America/New_York"));
}
public static String estToIst(String dateInput) throws ParseException {
return changeTimeZone(dateInput, TimeZone.getTimeZone("America/New_York"),
TimeZone.getTimeZone("Asia/Calcutta"));
}
private static String changeTimeZone(String dateInput, TimeZone sourceTimeZone,
TimeZone targetTimeZone) throws ParseException {
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy hh:mm a");
formatter.setTimeZone(sourceTimeZone);
Date date = formatter.parse(dateInput);
formatter.setTimeZone(targetTimeZone);
return formatter.format(date);
}
Test
String dateInput = "08/22/2016 02:21 AM";
System.out.println(dateInput);
System.out.println(istToEst("08/22/2016 02:21 AM"));
System.out.println(estToIst("08/22/2016 02:21 AM"));
Output
08/22/2016 02:21 AM
08/21/2016 04:51 PM
08/22/2016 11:51 AM
Set formatter to the source timezone before parsing (this is the step you are missing), then set it to the destination timezone before formatting, otherwise it parses it using the local timezone, which is IST for you.
Also you should just be able to return sDateInAmerica directly, you don't need to re-parse then re-format it a second time.
java.time
You are using troublesome old legacy date-time classes, now supplanted by the java.time classes.
We parse the input string as a LocalDateTime as it lacks any info about offset-from-UTC or time zone (offset plus rules for anomalies such as DST).
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM/dd/yyyy hh:mm a" );
LocalDateTime ldt = LocalDateTime.parse( input , f );
Apply a time zone to get an actual moment on the timeline, a ZonedDateTime object.
ZoneId zNewYork = ZoneId.of( "America/New_York" );
ZonedDateTime zdtNewYork = ldt.atZone( zNewYork );
To see the same moment through the lens of another time zone, another wall-clock time, adjust into another ZoneId. Notice that we are not going through another LocalDateTime as the purpose of that class is to forget any information about offset or time zone. We want the opposite, to use the info about time zone to adjust wisely between zones. So while New York is behind UTC by four hours, India is ahead of UTC by five and a half hours. So we need a total of nine and a half hour adjustment, which may include a change in date.
ZoneId zKolkata = ZoneId.of( "Asia/Kolkata" );
ZonedDateTime zdtKolkata = zdtNewYork.withZoneSameInstant( zKolkata ); // Same simultaneous moments on the timeline.
Generate String
You can generate a String in any format you desire to represent the date-time value.
String output = zdtKolkata.format( f );
Generally better to let java.time automatically localize for you.
Locale l = Locale.CANADA_FRENCH; // Or Locale.US, Locale.ITALY, etc.
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.MEDIUM ).withLocale( l );
String output = zdtKolkata.format( f );

How to convert date time from one time zone to another time zone

The records are getting saved according to time zone of US but if I want to show the same record back to user it should convert the server date time with(US Time Zone) to user's date time with user's Time Zone
If you type in google "Java date change timezone" or "Javascript date change timezone". You will have one of your results:
In Java (source: http://www.coderanch.com/t/417443/java/java/Convert-Date-one-timezone-another )
Date date = new Date();
DateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm:ss z");
formatter.setTimeZone(TimeZone.getTimeZone("CET"));
// Prints the date in the CET timezone
System.out.println(formatter.format(date));
// Set the formatter to use a different timezone
formatter.setTimeZone(TimeZone.getTimeZone("IST"));
// Prints the date in the IST timezone
System.out.println(formatter.format(date));
Javascript (source: http://www.techrepublic.com/article/convert-the-local-time-to-another-time-zone-with-this-javascript/6016329 )
// function to calculate local time
// in a different city
// given the city's UTC offset
function calcTime(city, offset) {
// create Date object for current location
d = new Date();
// convert to msec
// add local time zone offset
// get UTC time in msec
utc = d.getTime() + (d.getTimezoneOffset() * 60000);
// create new Date object for different city
// using supplied offset
nd = new Date(utc + (3600000*offset));
// return time as a string
return "The local time in " + city + " is " + nd.toLocaleString();
}
// get Bombay time
alert(calcTime('Bombay', '+5.5'));
java.time
The old date-time classes are poorly designed, confusing, and troublesome. Avoid them.
Use modern classes: the java.time framework built into Java 8 and later. Find back-ports for earlier Java 6 & 7 and for Android.
An Instant is a moment on the timeline in UTC.
Instant now = Instant.now();
Apply a time zone (ZoneId) to get a ZonedDateTime.
Never use the 3-4 letter zone abbreviations such as EST or IST. They are neither standardized nor unique(!). Use proper time zone names, built in a continent/region format such as Asia/Kolkata, Pacific/Auckland, America/Los_Angeles.
ZoneId zoneId_Montreal = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt_Montreal = ZonedDateTime.ofInstant( instant , zoneId_Montreal );
Apply a different time zone to generate another ZonedDateTime adjusted to that time zone. Call withZoneSameInstant.
ZoneId zoneId_Paris = ZoneId.of( "Europe/Paris" ); // Or "Asia/Kolkata", etc.
ZonedDateTime zdt_Paris = zdt_Montreal.withZoneSameInstant( zoneId_Paris );
If you want to go back to UTC, ask for an Instant.
Instant instant = zdt_Paris.toInstant();
TimeZone fromTimezone =TimeZone.getTimeZone(from);
TimeZone toTimezone=TimeZone.getTimeZone(to);
long fromOffset = fromTimezone.getOffset(calendar.getTimeInMillis());
long toOffset = toTimezone.getOffset(calendar.getTimeInMillis());
long convertedTime = calendar.getTimeInMillis() - (fromOffset - toOffset);
//Convert date from one zone to another
/*
$zone_from='Asia/Kolkata';
$zone_to='America/Phoenix';
date_default_timezone_set($zone_from);
$convert_date="2016-02-26 10:35:00";
echo $finalDate=zone_conversion_date($convert_date, $zone_from, $zone_to);
*/
function zone_conversion_date($time, $cur_zone, $req_zone)
{
date_default_timezone_set("GMT");
$gmt = date("Y-m-d H:i:s");
date_default_timezone_set($cur_zone);
$local = date("Y-m-d H:i:s");
date_default_timezone_set($req_zone);
$required = date("Y-m-d H:i:s");
/* return $required; */
$diff1 = (strtotime($gmt) - strtotime($local));
$diff2 = (strtotime($required) - strtotime($gmt));
$date = new DateTime($time);
$date->modify("+$diff1 seconds");
$date->modify("+$diff2 seconds");
return $timestamp = $date->format("Y-m-d H:i:s");
}
Code To Get Berlin Time and Convert it into UTC Time
Calendar sc = Calendar.getInstance(TimeZone.getTimeZone("Europe/Berlin"));
String strt = null;
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'");
sf.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
sc.set(sc.get(Calendar.YEAR),sc.get(Calendar.MONTH), sc.get(Calendar.DATE),sc.get(Calendar.HOUR) , sc.get(Calendar.MINUTE));
strt = sf.format(sc.getTime());
System.out.println("Start :"+strt);

Categories

Resources