Timezone is ignored when I trying to create new broadcast - android

I'm working with YouTube Live Streaming API.
And I had a problem, every time I create live broadcast and set its scheduledStartTime, the timezone I set is ignored. In requests response I receive DateTime with 0 timezone.
And again when I requesting list of upcoming broadcasts I receive broadcasts with timezone -0700.
No matter which timezone was on this broadcast, no matter from where request was executed - from Android/iOS mobile client, or via YouTube API explorer.
That is how I format my date:
String datePattern = "yyyy-MM-dd'T'HH:mm:ssZZZZZ";
DateFormat dateFormat = new SimpleDateFormat(datePattern);
dateFormat.setTimeZone(calendar.getTimeZone());
String dateFormatted = dateFormat.format(date); //2017-06-19T17:50:51+03:00
String iso8601Date = DateTime.parseRfc3339(dateFormatted);//2017-06-19T17:50:51.000+03:00
Maybe, problem is with my DateTime format pattern. But that is pattern of ISO 8601 date format representation. And I'm confused, why my timezone is ignored?

The old API (with Calendar and SimpleDateFormat classes) is outdated and has lots of problems.
You should consider using the newer API's. If you're using Java 8, consider using the new java.time API. It's easier, less bugged and less error-prone than the old APIs.
If you're using Java <= 7, you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. And for Android, there's the ThreeTenABP (more on how to use it here).
The code below works for both.
The only difference is the package names (in Java 8 is java.time and in ThreeTen Backport (or Android's ThreeTenABP) is org.threeten.bp), but the classes and methods names are the same.
If you're working with dates/times that contains an offset, the best choice is to use the OffsetDateTime class, which represents a date and time with an offset. And it already has a method to parse a String:
// parse a date string with offset -07:00
String strDate = "2017-06-19T17:50:51.000-07:00";
OffsetDateTime dt = OffsetDateTime.parse(strDate);
System.out.println(dt.toString()); // 2017-06-19T17:50:51-07:00
The output will be:
2017-06-19T17:50:51-07:00
Note that by default, the toString() method didn't show the fraction-of-seconds, because they're zero. If you want to always show these 3 digits, you can use a DateTimeFormatter:
// use a formatter to always print fraction-of-second with 3 digits
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ");
System.out.println(fmt.format(dt)); // 2017-06-19T17:50:51.000-07:00
In this case, the output will be:
2017-06-19T17:50:51.000-07:00
Testing with different offsets:
// offset +03:00
dt = OffsetDateTime.parse("2017-06-19T17:50:51.000+03:00");
System.out.println(fmt.format(dt)); // 2017-06-19T17:50:51.000+03:00
// UTC: "Z" == offset zero (or "+00:00")
dt = OffsetDateTime.parse("2017-06-19T17:50:51.000Z");
System.out.println(fmt.format(dt)); // 2017-06-19T17:50:51.000Z
dt = OffsetDateTime.parse("2017-06-19T17:50:51.000+00:00");
System.out.println(fmt.format(dt)); // 2017-06-19T17:50:51.000Z
If you still have to use the old API (java.util.Calendar), you can easily convert it to and from the new classes.
If the java.time package is available, you can do:
// converting the OffsetDateTime to a Calendar
dt = OffsetDateTime.parse("2017-06-19T17:50:51.000Z");
Calendar c = Calendar.getInstance();
// setting the epoch milli to calendar
c.setTimeInMillis(dt.toInstant().toEpochMilli());
// converting Calendar back to OffsetDateTime (using UTC offset)
dt = OffsetDateTime.ofInstant(c.toInstant(), ZoneOffset.UTC);
// converting Calendar back to OffsetDateTime (using +03:00 offset)
dt = OffsetDateTime.ofInstant(c.toInstant(), ZoneOffset.ofHours(3));
If you're using ThreeTenABP, the method c.toInstant() won't be available. But you can use org.threeten.bp.DateTimeUtils class to convert it. So, instead of c.toInstant() you can use DateTimeUtils.toInstant(c):
// conversion for ThreeTenABP
// converting Calendar back to OffsetDateTime (using UTC offset)
dt = OffsetDateTime.ofInstant(DateTimeUtils.toInstant(c), ZoneOffset.UTC);
// converting Calendar back to OffsetDateTime (using +03:00 offset)
dt = OffsetDateTime.ofInstant(DateTimeUtils.toInstant(c), ZoneOffset.ofHours(3));
Update: Youtube API
I checked at Youtube API documentation (not sure if that's what you're using) and in the examples it sets the scheduledStartTime to a date/time in UTC:
broadcastSnippet.setScheduledStartTime(new DateTime("2024-01-30T00:00:00.000Z"));
According to the docs, this field has the following format:
The date and time that the broadcast is scheduled to start. The value is specified in ISO 8601 (YYYY-MM-DDThh:mm:ss.sZ) format.
So, we just need to create a formatter to get the String in this format:
// your date/time, in -07:00 offset
String strDate = "2017-06-19T17:50:51.000-07:00";
OffsetDateTime odt = OffsetDateTime.parse(strDate);
// formatter
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSX");
// convert to UTC
String utc = formatter.format(odt.withOffsetSameInstant(ZoneOffset.UTC));
System.out.println(utc); // 2017-06-20T00:50:51.000Z
The output will be in the same format used in youtube's example:
2017-06-20T00:50:51.000Z

Related

toString() returns unexpected things on a Date object

I recently started coding my really first Android project using Android Studio 3.1.2 and SDK 19.
One of my Objects has Date attributes. At some points I want to display the whole date time or parts of it in a TextView. So I tried it the rookie way and called toString() on my Date.
However the displayed text contains elements I didn't define in the SingleDateFormat pattern I used to create the Date Object.
This is how I create the Date on myObject:
Date date1;
Date date2;
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
date1 = format.parse(json.getString("date_1"));
dtae2 = format.parse(json.getString("date_2"));
} catch(ParseException e) {
//error handling stuff
e.printStackTrace();
}
This is where I want to display the Date on a View:
myTextView.setText("First appearance logged at " + myObject.getDate1().toString());
I expected a String like 2018-08-16 12:14:42 to be displayed. Instead what I get is Thu Aug 12:14:42 GMT +02:00 2018. This seems to be another DateFormat and ignoring my custom pattern.
So my question is, if there's a way to manipulate the output of toString(), so the Date gets displayed in the way I defined in the pattern. Can I somehow pass the pattern to the toString() method?
EDIT
I changed the attributes of my Objects to String type, though it's way easier for presenting. The reason to convert them into a Date is, that I need to calculate the duration between the two guys, but that's not a problem i can't solve. Thanks to the community.
According to your need, you can just use json.getString("date_1").
You don't need to set extra logics. Parsing is needed when you want to convert String date to Date object for some calculation.
If you want to change format of received date then use this method.
changeStringDateFormat(json.getString("date_1"), "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd");
Just put this method inside your Util.
public String changeStringDateFormat(String date, String inputDateFormat, String outPutDateFormat) {
Date initDate = null;
try {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(inputDateFormat);
initDate = simpleDateFormat.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat outputFormatter = new SimpleDateFormat(outPutDateFormat);
String parsedDate = outputFormatter.format(initDate);
return parsedDate;
}
See Java Date Doc, It returns string from default format.
public String toString()
Converts this Date object to a String of the form:
dow mon dd hh:mm:ss zzz yyyy
Simply Write this code snippet
JAVA FILE
public class MainActivity extends AppCompatActivity {
TextView my_text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
my_text = findViewById(R.id.my_text);
String pattern = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
String date = simpleDateFormat.format(new Date());
Toast.makeText(getApplicationContext(), "" + date, Toast.LENGTH_SHORT).show();
my_text.setText("Your Date is : " + date);
}
}
XML FILE
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="mydemo.com.anew.MainActivity">
<TextView
android:id="#+id/my_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
See output:
See Screenshot of output same like your requirement get a current date:
Refer this Tutorial
Hope this may help to you
tl;dr
Use the modern java.time classes instead of the terrible legacy Date & SimpleDateFormat classes.
myJavaUtilDate // Never use `java.util.Date`.
.toInstant() // Convert from legacy class to modern replacement. Returns a `Instant` object, a moment in UTC.
.atOffset( // Convert from the basic `Instant` class to the more flexible `OffsetDateTime` class.
ZoneOffset.UTC // Constant defining an offset-from-UTC of zero, UTC itself.
) // Returns a `OffsetDateTime` object.
.format( // Generate a `String` with text representing the value of this `OffsetDateTime` object.
DateTimeFormatter.ISO_LOCAL_DATE_TIME // Pre-defined formatter stored in this constant.
) // Returns a `String` object.
.replace( "T" , " " ) // Replace the standard `T` in the middle with your desired SPACE character.
2018-08-16 10:14:42
java.time
You are using terrible old classes that were supplanted years ago by the java.time classes.
If handed a java.util.Date object, immediately convert to java.time.Instant. Both represent a moment in UTC. Instant has a finer resolution of nanoseconds rather than milliseconds.
To convert between the legacy and modern classes, look to new conversion methods added to the old classes.
Instant
Instant instant = myJavaUtilDate.toInstant() ; // New method on old class for converting to/from java.time classes.
ISO 8601
To generate a String with text in standard ISO 8601 format similar to your desired format, call toString.
String output = instant.toString() ; // Generate text in standard ISO 8601 format.
Elapsed time = Duration
By the way, to calculate elapsed time, use the Duration classes. Pass a pair of Instant objects to calculate the number of 24-hour "days", hours, minutes, and seconds elapsed.
Duration d = Duration.between( start , stop ) ; // Calc elapsed time.
2018-08-16T10:14:42Z
OffsetDateTime
For other formatting, convert from the basic Instant class to the more flexible OffsetDateTime class.
OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC ) ;
odt.toString(): 2018-08-16T10:14:42Z
DateTimeFormatter
Your desired format is close to the predefined formatter DateTimeFormatter.ISO_LOCAL_DATE_TIME. Just replace the T in the middle with a SPACE.
String output = odt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )
.replace( "T" , " " ) ;
2018-08-16 10:14:42
ZonedDateTime
Keep in mind that we are only looking at UTC so far. For any given moment, the date and the time-of-day both vary around the globe by zone.
If you want to see that same moment through the lens of the wall-clock time used by the people of a certain region (a time zone), then apply a ZoneId to get a ZonedDateTime object.
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
zdt.toString(): 2018-08-16T11:14:42+01:00[Africa/Tunis]
You can use the same formatter as seen above to generate a string in your desired format.
String output = zdt.format( f ) ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
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.
You need to use SimpleDateFormat something like this:
String myFormat = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
myTextView.setText("First appearance logged at " + sdf.format(date1));
In my project I've been formatting using the format() function, like so:
myTextView.setText("First appearance logged at " + format.format(myObject.getData1()));
I hope that helps.

Getting 4 hours difference while getting while converting data in to device timezone?

I am getting the 4 hours difference on time zone from below lines of code on my device:
I am getting the time in such a way like 2018-09-30T13:45:00Z
My start and End Date is as follow: -
"start_date":"2017-09-13T12:15:00Z",
"end_date":"2018-09-30T13:45:00Z",
Calendar c = Calendar.getInstance(Locale.getDefault());
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
Date localStartDate = formatter.parse(startTime);
Date localEndDate = formatter.parse(endTime);
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm");
dateFormatter.setTimeZone(c.getTimeZone());
localStartDate = dateFormatter.parse(startTime);
localEndDate = dateFormatter.parse(endTime);
SimpleDateFormat monthFormat = new SimpleDateFormat("MMM");
monthFormat.setTimeZone(TimeZone.getTimeZone(TimeZone.getDefault().getDisplayName()));
String monthName = monthFormat.format(localStartDate);
eventDate.setMonth(monthName);
SimpleDateFormat dateFormat = new SimpleDateFormat("dd");
dateFormat.setTimeZone(TimeZone.getTimeZone(TimeZone.getDefault().getDisplayName()));
String dateName = dateFormat.format(localStartDate);
eventDate.setDate(dateName);
SimpleDateFormat dayNameFormat = new SimpleDateFormat("EEEE");
dayNameFormat.setTimeZone(TimeZone.getTimeZone(TimeZone.getDefault().getDisplayName()));
String dayName1 = dayNameFormat.format(localStartDate);
String dayName2 = dayNameFormat.format(localEndDate);
eventDate.setDayName1(dayName1);
eventDate.setDayName2(dayName2);
SimpleDateFormat timeFormat = new SimpleDateFormat("hh:mm a");
timeFormat.setTimeZone(TimeZone.getTimeZone(TimeZone.getDefault().getDisplayName()));
String startTimeName = timeFormat.format(localStartDate);
String endTimeName = timeFormat.format(localEndDate);
System.out.println("My Start date and end date==>>>"+startTimeName+" " +endTimeName );
Problem: Getting the 4 hours difference from above code, as I am setting my time zone to BOSTON(US), getting error.
My result from the below #Hugo solution is as below
And i am expecting the result as below
Please check it once..I have also set the TimeZone of Eastern DayLight Time but not getting proper solution..please check it once..And let me know
SimpleDateFormat and Calendar uses the JVM default timezone (unless you set a different one on them), and the default timezone can be different in each device/machine/environment. Not only that, this default can be changed without notice, even at runtime, so it's better to always make it explicit which one you're using.
When you do things like:
Calendar c = Calendar.getInstance(Locale.getDefault());
dateFormatter.setTimeZone(c.getTimeZone());
monthFormat.setTimeZone(TimeZone.getTimeZone(TimeZone.getDefault().getDisplayName()));
The Calendar is created with the default timezone, so dateFormatter will also have the same zone. So does monthFormat, and also the other formatters you created. The only formatter set to a different zone is the first one (which is set to UTC).
Also, the second formatter is redundant (it does the same thing that the first one is already doing: parsing the String to a Date), so you can remove it.
Assuming that your input is a String with the value 2018-09-30T13:45:00Z: the Z in the end indicates that this date is in UTC. So you should parse it using a formatter set to UTC. So, instead of using c.getTimeZone() and TimeZone.getDefault(), you should use only TimeZone.getTimeZone("UTC").
For the output, you must set the formatters with the timezone you want to convert to. If the timezone is "EDT", set to it (but don't use exactly "EDT", see below). If you want to use the JVM default, use TimeZone.getDefault() - just check this value before, to make sure the default is what you need.
Just keep in mind that short names like "EDT" and "EST" are not real timezones. Those abbreviations are ambiguous and not standard. Prefer to use IANA timezones names (always in the format Region/City, like America/New_York or Europe/Berlin).
So, when you do TimeZone.getTimeZone("EDT"), it usually returns "GMT" (because "EDT" is not recognized, and "GMT" is returned as default). That's because "EDT" is used by more than one timezone, so you must choose specifically which one you're using (I'm using America/New_York in these examples).
Another detail is that in the first 2 formatters you use hh, which means "hour of am/pm" (values from 1 to 12), but the input doesn't have AM/PM designators to properly resolve this. You need to change it to HH ("hour of day", with values from 0 to 23).
// input is in UTC
TimeZone inputZone = TimeZone.getTimeZone("UTC");
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
formatter.setTimeZone(inputZone);
Date localStartDate = formatter.parse(startTime);
Date localEndDate = formatter.parse(endTime);
...
// removed the second formatter (it was redundant)
// output is in EST (America/New_York)
// or use TimeZone.getDefault() to get JVM default timezone
TimeZone outputZone = TimeZone.getTimeZone("America/New_York");
SimpleDateFormat monthFormat = new SimpleDateFormat("MMM");
monthFormat.setTimeZone(outputZone);
...
SimpleDateFormat dateFormat = new SimpleDateFormat("dd");
dateFormat.setTimeZone(outputZone);
...
SimpleDateFormat dayNameFormat = new SimpleDateFormat("EEEE");
dayNameFormat.setTimeZone(outputZone);
...
SimpleDateFormat timeFormat = new SimpleDateFormat("hh:mm a");
timeFormat.setTimeZone(outputZone);
...
System.out.println("My Start date and end date==>>>" + startTimeName + " " + endTimeName);
With this, you're explicity using UTC for input and a specific timezone for output, instead of relying on the JVM default timezone (which can be different in each device and you can't control).
The output is:
My Start date and end date==>>>08:15 AM 09:45 AM
Java new Date/Time API
The old classes (Date, Calendar and SimpleDateFormat) have lots of problems and design issues, and they're being replaced by the new APIs.
In Android you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. To make it work, you'll also need the ThreeTenABP (more on how to use it here).
First you can use a org.threeten.bp.Instant to parse the input, because it's in UTC (designated by the Z in the end). Then you use a org.threeten.bp.ZoneId to convert it to a org.threeten.bp.ZonedDateTime:
// output timezone
// or use ZoneId.systemDefault() to get JVM default timezone
ZoneId zone = ZoneId.of("America/New_York");
// parse the inputs
ZonedDateTime startDate = Instant.parse(startTime).atZone(zone);
ZonedDateTime endDate = Instant.parse(endTime).atZone(zone);
Then you can use these objects to get the other fields:
// get month name
System.out.println(startDate.getMonth().getDisplayName(TextStyle.SHORT, Locale.getDefault()));
This is equivalent to MMM pattern, and it will print the month name in the default locale. If you want the month name in a specific language, just use another java.util.Locale value (such as Locale.ENGLISH or any other one as described in the javadoc).
The org.threeten.bp.format.TextStyle defines if the month name will be narrow (usually just one letter), short (usually 2 or 3 letters) or full (the full name). The output varies according to the locale used.
I personally prefer to not use the default locale, because it can be changed without notice, even at runtime. It's always better to specify the locale you want.
To get the day of month, you can choose to get it as an int or as a formatted String (using a org.threeten.bp.format.DateTimeFormatter):
// get day of month as int
int day = startDate.getDayOfMonth(); // 30
// get day of month as formatted string
String dayStr = DateTimeFormatter.ofPattern("dd").format(startDate); // 30
To get the day of week, it's similar to the code used to get the month:
// get day of week
System.out.println(startDate.getDayOfWeek().getDisplayName(TextStyle.FULL, Locale.getDefault()));
The same logic applies here: the TextStyle defines how the name will be (in this case, FULL is equivalen to EEEE, and it prints the full name), and the locale defines the language used.
Finally, to get the corresponding time, you can use another DateTimeFormatter:
// get time
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("hh:mm a");
System.out.println(fmt.format(startDate)); // 08:15 AM
System.out.println(fmt.format(endDate)); // 09:45 AM
This will the date/time in the timezone you chose for the output.
If you're going to use the JVM default (ZoneId.systemDefault()), just check its value before to make sure it's the one you want (it might not be because this can be changed at runtime, so it's always better to specify one).

Android, Right way to programticly format date time as time ago

Example, from 1 min ago
i use api and time response result from Api service as:
{
"date_time":"2016-03-10 03:20:30"
}
Please discuss step by step, And if available how can programticly display it in Arabic format
منذ 15 دقيقة
My Code for date in list view adapter
TextView date_time = (TextView) convertView.findViewById(R.id.date_time_list_home);
date_time.setText(m.dateTime());
First, for any date/time manipulation on Android, I highly recommend using the ThreeTenABP library. This is a back port of the Java 8 java.time.* package, circumventing the notoriously disappointing java.util.Date and java.util.Calendar classes.
To parse your "date_time" using this library, you can use the following code:
// I set the ZoneId to systemDefault, but you should really use the ZoneId of the server
DateTimeFormatter formatter = DateTimeFormatter
.ofPattern("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
.withZone(ZoneId.systemDefault());
Instant instant = formatter.parse(m.dateTime(), Instant.FROM);
Android provides the DateUtils class to display date and time information. This class takes into account system settings such as Locale and 12/24-hour format. Therefore, if the Locale of the device is set to any of the Arabic locales (ar_), the date/time will be displayed in a format suited for it.
String display = DateUtils.getRelativeTimeSpanString(
instant.toEpochMilli(),
Instant.now().toEpochMilli(),
DateUtils.MINUTE_IN_MILLIS);
date_time.setText(display);
The last parameter in getRelativeTimeSpanString is the minimum resolution, so setting DateUtils.MINUTE_IN_MILLIS will not display the difference in seconds.
If you insist on using the Java 7 classes, here is the same code using them:
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = format.parse(m.dateTime());
String display = DateUtils.getRelativeTimeSpanString(
date.getTime(),
new Date(),
DateUtils.MINUTE_IN_MILLIS);
date_time.setText(display);
If you need a "transition resolution" greater than a single day (i.e. you want to display a date/time that is further than one day in the past as "… days ago") you can use the DateUtils.getRelativeDateTimeString() method instead:
String display = DateUtils.getRelativeDateTimeString(
mContext,
instant.toEpochMilli(),
DateUtils.MINUTE_IN_MILLIS,
DateUtils.WEEK_IN_MILLIS,
DateUtils.FORMAT_ABBREV_ALL);
Any date that is further back than the transitionResolution (in this case, one week) will be displayed in an appropriate date format, instead of the relative format. The minResolution and transitionResolution can be any long value, DateUtils contains other convenient constants such as MONTH_IN_MILLIS and YEAR_IN_MILLIS.
The last parameter takes an integer for formatting flags. These flags override the default formatting that DateUtils uses for each Locale; view the documentation for more information.

Getting the same hours:minutes in Android

Every time I try to get the current time (I have a button for that, lets call it "botonGuardarEstado") I get the same hours and minutes. What I have noted is that the time I got is the time when I opened the app. What I mean is, if I opened the app at 7:10 a.m. and press the button at 7:12 a.m., I get 7:10 a.m. Here is my code:
DateFormat formatoFecha = new SimpleDateFormat("HH:mm dd/MM/yyyy");
String fecha = formatoFecha.format(Calendar.getInstance().getTime());
I am not getting weird values like different years or anything like that, and the format works well, the problem is that i get the same hours:minutes everytime i push the button. I alredy tried different ways of getting the date and time, things like Date(), or even getting only the hours and minutes using something like this
Calendar cal = Calendar.getInstance();
int mins = cal.get(Calendar.MINUTE);
but still got the same values.
I have the following class
private class InfoArchivo {
String temperatura, humedad, gas, humo, iluminacion, riego, ventilacion, fecha;
public InfoArchivo(String temperatura, String humedad, String gas, String humo, String iluminacion, String riego, String ventilacion, String fecha){
this.temperatura = temperatura;
this.humedad = humedad;
this.gas = gas;
this.humo = humo;
this.iluminacion = iluminacion;
this.riego = riego;
this.fecha = fecha;
if(!ventilacion.equals("0"))
this.ventilacion = "1";
else
this.ventilacion = "0";
}
I have an array of instances of that class. What i am trying to do is write a csv file using the array. Every other data (temperatura, humedad, etc) is correct. The only thing causing trouble is the date (fecha). The creation of the csv file is done until i press another button. When i press the botonGuardarEstado button i get the date, make an instance of the class InfoArchivo and add it to the array
EDIT: Also tried with this but still have the same issue:
Instant instant = Instant.now();
ZoneId zoneId = ZoneId.of("America/Guatemala");
ZonedDateTime zdt = ZonedDateTime.ofInstant(instant, zoneId);
DateTimeFormatter formato = DateTimeFormatter.ofPattern("HH:mm dd/MM/yyyy");
String fecha = zdt.format(formato);
Not a date-time problem
Your code as shown is correct.
So your problem must be happening elsewhere in your app. Perhaps you are not correctly feeding the new String (fecha) to the user interface. Or perhaps you need to do something to refresh the display of that new String’s value. We cannot help you further as you did not provide that other code.
java.time
By the way, you are using outmoded classes. The old date-time classes that have proven to be so confusing and troublesome have been supplanted by the java.time framework. See the Oracle Tutorial.
Java 8 and later: The java.time framework is built-in.
Java 7 & 6: Use the backport of java.time.
Android: Use this wrapped version of that backport.
Instant
An Instant is a moment on the timeline in UTC with resolution up to nanoseconds.
Instant instant = Instant.now(); // Current moment in UTC.
Time Zone
Apply a time zone (ZoneId) to get a ZonedDateTime. If you omit the time zone your JVM’s current default time zone is implicitly applied. Better to specify explicitly the desired/expected time zone.
ZoneId zoneId = ZoneId.of( "America/Montreal" ); // Or "Asia/Kolkata", "Europe/Paris", and so on.
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );
Generating Strings
You can easily generate a String as a textual representation of the date-time value. You can go with a standard format, your own custom format, or an automatically localized format.
ISO 8601
You can call the toString methods to get text formatted using the common and sensible ISO 8601 standard.
String output = instant.toString();
2016-03-19T05:54:01.613Z
Custom format
Or specify your own particular formatting pattern with the DateTimeFormatter class.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "dd/MM/yyyy hh:mm a" );
Specify a Locale for a human language (English, French, etc.) to use in translating the name of day/month and also in defining cultural norms such as the order of year and month and date. Note that Locale has nothing to do with time zone.
formatter = formatter.withLocale( Locale.US ); // Or Locale.CANADA_FRENCH or such.
String output = zdt.format( formatter );
Localizing
Better yet, let java.time do the work of localizing automatically.
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.MEDIUM );
String output = zdt.format( formatter.withLocale( Locale.US ) ); // Or Locale.CANADA_FRENCH and so on.

Convert string Date into timestamp in Android?

I want to convert my date (which is in String format), e.g. 13-09-2011, into Timestamp. I used below code but I got the 2011-09-13 00:00:00.0
as a result. But I want Timestamp like,1312828200000 format.
I cannot understand how to convert that.
My code:
String str_date="13-09-2011";
DateFormat formatter ;
Date date ;
formatter = new SimpleDateFormat("dd-MM-yyyy");
date = (Date)formatter.parse(str_date);
java.sql.Timestamp timeStampDate = new Timestamp(date.getTime());
System.out.println("Today is " +timeStampDate);
If you use getTime() of Date object you will get time in millisecond.
No need to use Timestamp to get your result.
String str_date="13-09-2011";
DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
Date date = (Date)formatter.parse(str_date);
System.out.println("Today is " +date.getTime());
The above code will print something like 1312828200000 you need and this is long value.
String str_date=month+"-"+day+"-"+yr;
DateFormat formatter = new SimpleDateFormat("MM-dd-yyyy");
Date date = (Date)formatter.parse(str_date);
long output=date.getTime()/1000L;
String str=Long.toString(output);
long timestamp = Long.parseLong(str) * 1000;
This line:
"Today is " +timeStampDate
calls TimeStamp.toString() method "which Formats a timestamp in JDBC timestamp escape format. yyyy-mm-dd hh:mm:ss.fffffffff, where ffffffffff indicates nanoseconds."
The TimeStamp you got internally has the value you want. If you want to get it than use:
System.out.println("Today is " + timeStampDate.getTime());
String str_date="13-09-2011";
DateFormat formatter ;
Date date ;
formatter = new SimpleDateFormat("dd-MM-yyyy");
date = (Date)formatter.parse(str_date);
java.sql.Timestamp timeStampDate = new Timestamp(date.getTime());
System.out.println("Today is " + timeStampDate.getTime());
Or if you don't need the Timestamp, you can directly use date.getTime(). It "Returns the Date as a millisecond value.":
String str_date="13-09-2011";
DateFormat formatter ;
Date date ;
formatter = new SimpleDateFormat("dd-MM-yyyy");
date = (Date)formatter.parse(str_date);
System.out.println("Today is " + date.getTime());
tl;dr
Use modern java.time classes.
LocalDate.parse(
"13-09-2011" ,
DateTimeFormatter.ofPattern( "dd-MM-uuuu" )
)
.atStartOfDay(
ZoneId.of( "Africa/Casablanca" ) // Or use `ZoneOffset.UTC` instead of a zone.
)
.toInstant()
.toEpochMilli()
See this code run live at IdeOne.com.
1315872000000
Details
Apparently you want to represent the first moment of a particular date as a count of milliseconds since the epoch reference of first moment of 1970 in UTC.
java.time
The modern approach uses the java.time classes that years ago supplanted the troublesome legacy classes such as Date, Calendar, and SimpleDateFormat.
First parse your input string as a LocalDate, for a date-only value without time-of-day and without time zone.
Tip: Rather then using such custom formats when exchanging date-time values as text, use standard ISO 8601 formats. The java.time classes use them by default when parsing/generating strings.
String input = "13-09-2011" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MM-uuuu" ) ;
LocalDate ld = LocalDate.parse( input , f ) ;
Determine the first moment of the day on that date. Doing so requires a time zone. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment during runtime(!), so your results may vary. Better to specify your desired/expected time zone explicitly as an argument.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
Never assume the day starts at 00:00. In some zones on some dates, the day may start at another time such as 01:00. Let java.time determine first moment.
ZonedDateTime zdt = ld.startOfDay( z ) ; // Determine first moment of the day on this date in this zone. May not be 00:00.
Adjust to UTC from that zone by extracting a Instant.
Instant instant = zdt.toInstant() ;
Get a count of milliseconds since 1970-01-01T00:00Z. Beware of possible data loss, as an Instant carries a finer resolution of nanoseconds. Any microseconds or nanoseconds will be ignored.
long millisecondsSinceEpoch = instant.toEpochMilli() ;
You can go back the other direction, from a count-from-epoch to a Instant.
Instant instant = Instant.ofEpochMilli( millisecondsSinceEpoch) ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
Kotlin
val dateString = "17-09-2021"
val formatter = SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH)
val date = formatter.parse(dateString) as Date
Log.i("i","Today is " + date.time)
You'll get something that resembles 1616668471659
It may can help you
long time= System.currentTimeMillis();//timestamp in milliseconds of current time
String tp = Long.toString(time);//use timestamp as a string

Categories

Resources