I must convert a linux timestamp to android date.
i get this number from server
1386889262
I have written a small code snippet.
Date d = new Date(jsonProductData.getLong(MTIME));
SimpleDateFormat f = new SimpleDateFormat("dd.MM.yyyy");
.setTimeZone(TimeZone.getTimeZone("GMT"));
formatTime = f.format(d);
but it doesen't convert right, this is my result
17.01.1970
EDIT:
Normally i must get this here
12.12.2013
Is there an another method to get the right date???
if your UNIX time stamp is of 10 digit then it does not include milliseconds so do this first 1386889262*1000
and if its 13 digit then it includes milliseconds also then you do not have to multiply unix timestamp with 1000.
In Kotlin we can use this function:
val unix=1386889262*1000 /*if time stamp is of 10 digit*/
val dateFormat = SimpleDateFormat("dd-MM-yy HH:mm:ss");
val dt = Date(unix);
textview.settext(dateFormat.format(dt))
UNIX timestamp should be in milliseconds so multiply the Long value by 1000. So your value 1386889262 would be 1386889262000:
tl;dr
Instant.ofEpochSecond( 1386889262L )
.atZone( ZoneId.of( "Pacific/Auckland" ) )
.toLocalDate()
.toString()
java.time
You appear to have a count of whole seconds from the epoch reference date of first moment of 1970 in UTC, 1970-01-01T00:00:00Z.
The modern approach uses the java.time classes that supplant the troublesome old date-time classes bundled with the earliest versions of Java. For older Android see the ThreeTen-Backport and ThreeTenABP projects.
An Instant represents a point on the timeline in UTC with a resolution of nanoseconds (up to nine digits of decimal fraction).
Instant instant = Instant.ofEpochSecond( 1386889262L ) ;
To generate a String representing this moment, call toString.
String output = instant.toString() ;
Determining a date requires a time zone. For any given moment, the date varies around the globe by zone. Assign a ZoneId to get a ZonedDateTime object.
ZoneId z = ZoneId.of( "Africa/Casablanca" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
Extract a date-only value for your purposes.
LocalDate ld = zdt.toLocalDate() ;
Generate a String.
String output = ld.toString() ;
For other formats in your String, search Stack Overflow for DateTimeFormatter.
Your timestamp or epoch time seems in sec "1386889262". You have to do something like this:
long date1 = 1386889262*1000;
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yy HH:mm");
Date dt = new Date(date1);
datedisplay.setText(dateFormat.format(dt));
You can also get timestamp in java via
new Date().getTime() ;
It returns a long value.
Related
I'm trying to make a code that tells me how many days left for me to go college, but I am not able to do it with the current date. I can easily make it by setting a date, but I want the current date, so I have to use the calendar method, but can't do math using it.
My code:
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Calendar calendar = Calendar.getInstance();
Date start = sdf.parse("10/06/2022");
System.out.println(start - calendar.getTime());
tl;dr
ChronoUnit.DAYS.between(
LocalDate.now( ZoneId.of( "Pacific/Auckland" ) ) ,
LocalDate.parse( "10/06/2022" , DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) )
)
Details
You are using terrible date-time classes that were years ago supplanted by the modern java.time classes defined in JSR 310. Never use Date/Calendar.
Also, you are attempting to use a date-time class representing a date with time-of-day as seen in UTC (offset of zero) to hold a date-only value. Square peg, round hole.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ;
LocalDate graduationDate = LocalDate.parse( "10/06/2022" , f ) ;
Determine today's date. That requires a time zone. For any given moment, the date varies around the globe by time zone.
ZoneId z = ZoneId.of( "Asia/Tokyo" ) ; // Or ZoneId.systemDefault()
LocalDate today = LocalDate.now( z ) ;
Calculate elapsed time using java.time.temporal.ChronoUnit.
long days = ChronoUnit.DAYS.between( today , graduationDate ) ;
See this code run live at IdeOne.com.
graduationDate: 2022-06-10
today: 2022-03-05
days: 97
Tip: Learn about the ISO 8601 standard for exchanging date-time values as text.
Calendar calendar = Calendar.getInstance();
Calendar collegeDate = Calendar.getInstance();
collegeDate.set(Calendar.DATE,10);
collegeDate.set(Calendar.MONTH, 5);
collegeDate.set(Calendar.YEAR, 2022);
System.out.println(Duration.between(calendar.toInstant(), collegeDate.toInstant()).toDays());
You can try this
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Calendar calendar = Calendar.getInstance();
Date start = sdf.parse("10/06/2022");
long dif = Math.abs(calendar.getTimeInMillis() - start.getTime());
long result = TimeUnit.DAYS.convert(dif, TimeUnit.MILLISECONDS);
System.out.println(result);
I want to convert a timestamp (which is in GMT) to a local date and time.
This is what I have implemented so far, but it is giving me wrong month
Timestamp stp = new Timestamp(1640812878000L);
Calendar convertTimestamp = convertTimeStamp(stp,"America/Phoenix");
System.out.println(convertTimestamp.getTime());
public static Calendar convertTimeStamp( Timestamp p_gmtTime, String p_timeZone) throws Exception {
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy HH:MM:SS a", Locale.ENGLISH);
DateFormat formatter = DateFormat.getDateTimeInstance();
if (p_timeZone != null) {
formatter.setTimeZone(TimeZone.getTimeZone(p_timeZone));
} else {
formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
}
String gmt_time = formatter.format(p_gmtTime);
Calendar cal = Calendar.getInstance();
cal.setTime(sdf.parse(gmt_time));
return cal;
}
Any help would be appreciated.
You cannot convert a timestamp to another timezone, cause timestamps are always GMT, they are a given moment in the line of time in the universe.
We humans are used to local time on our planet, so a timestamp can be formatted to be more human readable, and in that context it is converted to a local timezone.
Using legacy java.util.* packages, this is done as follows:
DateFormat tzFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
tzFormat.setTimeZone(TimeZone.getTimeZone("CET")); // Use whatever timezone
System.out.println(tzFormat.format(date));
If you need to make "math" over the timestamp on local timezone (like, tomorrow at 8:00 local timezone), then the situation is more complex.
To do this you can resort to a number of hacks (like parsing or modifying the string obtained with the method above), or use the new Java date & time classes that have a specific class to deal with date and time in local time zones:
Instant timestamp = Instant.ofEpochMilli(inputValue);
ZonedDateTime romeTime = timestamp.atZone(ZoneId.of("Europe/Rome"));
Note how this second example uses "Europe/Rome" and not generically "CET". This is very important if you're planning to deal with timezones where DST is used, cause the DST change day (or if they use DST or not) may change from country to country even if they are in the same timezone.
tl;dr
Instant
.ofEpochMilli( // Parse a count of milliseconds since 1970-01-01T00:00Z.
1_640_812_878_000L
) // Returns a `Instant` object.
.atZone( // Adjust from UTC to a time zone. Same moment, same point on the timeline, different wall-clock time.
ZoneId.of( "America/Phoenix" )
) // Returns a `ZonedDateTime` object.
.format( // Generat text representing the date-time value kept within that `ZonedDateTime` object.
DateTimeFormatter
.ofLocalizedDateTime( FormatStyle.MEDIUM )
.withLocale( Locale.US )
) // Returns a `String` object.
See this code run live at IdeOne.com.
Dec 29, 2021, 2:21:18 PM
Details
You are using terrible old date-time classes that were years ago supplanted by the modern java.time classes defined in JSR 310. Never use Timestamp, Calendar, Date, SimpleDateFormat, etc.
Use the Instant class to represent a moment as seen in UTC, with an offset of zero hours-minutes-seconds.
long millisecondsSinceBeginningOf1970InUtc = 1_640_812_878_000L ;
Instant instant = Instant.ofEpochMilli( millisecondsSinceBeginningOf1970InUtc ) ;
Specify the time zone in which you are interested.
ZoneID z = ZoneId.of( "Africa/Tunis" ) ;
Adjust from offset of zero to that time zone to produce a ZonedDateTime object.
ZonedDateTime zdt = instant.atZone( z ) ;
Generate text representing that moment by automatically localizing. Use a Locale to specify the human language to use in translation as well as a culture to use in deciding abbreviation, capitalization, order of elements, and so on.
Locale locale = Locale.JAPAN ; // Or Locale.US, Locale.ITALY, etc.
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.LONG ).withLocale( locale ) ;
String output = zdt.format( f ) ;
All of this has been addressed many times on Stack Overflow. Search to learn more.
Following zulu date string is given:
2013-12-18T23:41:54.959Z
And I want to convert this to GMT and retrieve the minutes using Joda-Time. I build following method:
public static int minutesFromDateString(final String s){
DateTimeFormatter formatter = DateTimeFormat.forPattern("HH:mm").withZone(DateTimeZone.forID("Europe/Berlin"));
DateTime dt = formatter.parseDateTime(s);
Calendar calendar = Calendar.getInstance();
calendar.setTime(dt.toDate());
return calendar.get(Calendar.MINUTE);
}
However this returns an error:
12-22 16:04:11.940: E/AndroidRuntime(6433):
java.lang.IllegalArgumentException: Invalid format:
"2013-12-18T23:41:54.959Z" is malformed at "13-12-18T23:41:54.959Z"
Any ideas whats wrong?
You aren't using a valid pattern. Your pattern says it is looking for HH:mm, your real string is far more complex. Look at the DateTimeFormat docs. It looks like you want something like this: "yyyy-mm-dd'T'HH:mm:ss.SSS'Z'"
Just set proper pattern: "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
In your case:
public static int minutesFromDateString(final String s){
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ").withZone(DateTimeZone.forID("Europe/Berlin"));
DateTime dt = formatter.parseDateTime(s);
Calendar calendar = Calendar.getInstance();
calendar.setTime(dt.toDate());
return calendar.get(Calendar.MINUTE);
}
Output:
41
See docs HERE
The answer by PearsonArtPhoto is correct. To add more…
Joda-Time
With Joda-Time, no need for format pattern, and no need for Calendar class. You are working too hard.
The DateTime class takes an ISO 8601 string directly in its constructor.
Call the getMinuteOfHour method on a DateTime to extract just that portion.
If you want UTC/GMT rather than a specific time zone, pass the built-in constant, DateTimeZone.UTC. Be aware that time zone could affect your minute-of-hour. Not all time zones adjust by full hours. India for example has an offset of five and a half hours ahead of UTC/GMT (+05:30).
String input = "2013-12-18T23:41:54.959Z";
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Berlin" ); // Or, DateTimeZone.UTC;
DateTime dateTime = new DateTime( input, timeZone );
int minuteOfHour = dateTime.getMinuteOfHour();
Dump to console…
System.out.println( "dateTime: " + dateTime );
System.out.println( "minuteOfHour: " + minuteOfHour );
When run…
dateTime: 2013-12-19T00:41:54.959+01:00
minuteOfHour: 41
java.time
Joda-Time has been officially replaced by the java.time framework built into Java 8 and later. While Joda-Time continues to be updated, future work will go into the java.time classes and their extension, ThreeTen-Extra project.
Much of java.time has been back-ported to Java 6 & 7 in the ThreeTen-Backport project. That work is adapted to Android in the ThreeTenABP project.
The discussion above applies to a java.time solution. An Instant is a moment on the timeline in UTC. Apply a time zone ZoneId to get a ZonedDateTime.
String input = "2013-12-18T23:41:54.959Z";
Instant instant = Instant.parse( input );
ZoneId zoneId = ZoneId.of( "Europe/Berlin" ); // Or, ZoneOffset.UTC;
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant, zoneId );
int minuteOfHour = zdt.getMinute(); // Gets the minute-of-hour field.
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 ) ;
Can anybody tell me how to convert date to epoch in java.
e.g. 2011-05-01 13:12:20 IST or 2011-05-01 14:11:10 PST to epoch.
I am able to convert using 2011-05-01 13:12:20 format but when I use timezone alongwith it I am not getting correct result.
Construct a SimpleDateFormat with a string pattern that matches the date format you have. The "Date and Time" section and the "Examples" section should give you more than enough help on how to construct your date format string
Then simply do the following to get your date (with the appropriate date format string).
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date date = sdf.parse("15/01/2012");
java.time
Using the java.time classes.
String input = "2011-05-01 13:12:20".replace( " " , "T" );
LocalDateTime ldt = LocalDateTime.parse( input );
ZonedDateTime zdt = ldt.atZone( ZoneId.of( "Asia/Kolkata" ) );
If by “epoch”, you mean a count of whole seconds or milliseconds from the epoch reference date of first moment of 1970 in UTC (often referred to as Unix Time), then interrogate the ZonedDateTime object via an extracted Instant object.
long wholeSecondsSinceEpoch = zdt.toInstant().getEpochSecond();
long millisecondsSinceEpoch = zdt.toInstant().toEpochMilli();