Date Formatting2:10 with Ben Deitch
In this video we'll format our dates so that they look great for anyone anywhere in the world!
Our app is looking awesome. 0:00 We've added Spanish terms for all of our UI strings and 0:02 we've even updated the formatting of our price. 0:04 But before we move on to localizing for Egypt, 0:07 let's take another look at the date that shows up when we click on the Buy button. 0:10 Right now, if we click on the Buy button, the app confirms that our order was 0:13 received and it tells us the date and time it received the order. 0:17 Let's change this to only show the date and 0:22 let's also make sure that we're using the correct date format for each locale. 0:25 To do this we need to make use of the date format class, 0:29 which works very similarly to the number format class we used earlier. 0:32 Over in MainActivity, inside our buyButton's OnClickListener, let's update 0:37 our date string to be correctly formatted for the locale of our user. 0:41 So instead of setting this equal to date.toString, let's set this equal 0:46 to DateFormat.getDateInstance( ).format and pass in our date. 0:52 And if we run the app at this point, and click on the Buy button, 0:57 we only get the date, but it's not quite in the format we want. 1:05 We're looking for 1:09 the date to only contain numbers, luckily this is pretty easy to do. 1:10 Back in MainActivity, where we call getDateInstance, 1:15 we just need to pass in DateFormat.SHORT. 1:18 And if we run the app again 1:21 and click the Buy button, now we get the month, the day and year. 1:27 Just like we would expect for a locale based in the United States. 1:33 And if we change the language to Spanish, specifically 1:37 Spanish from Spain and then click the Buy button again. 1:42 Now we start with the day and then the month and 1:51 then the year, which is exactly how it should look for user based in Spain. 1:54 So all we had to do to support displaying dates from all over the world 1:58 was use the date format object. 2:03 Android knows what locale or users are in and 2:05 displays the correct date format automatically. 2:07
You need to sign up for Treehouse in order to download course files.Sign up