This question is not for generic Java, but only for Codename One.
I know that the L10NManager class provides the methods formatDateLongStyle, formatDateShortStyle, formatDateTime, formatDateTimeMedium, formatDateTimeShort, but their output is inconsistent between platforms (Simulator, Android, iOS, etc.). Moreover, even if their output could be consistent, it's not exactly as I need it.
I need to format the output localized string exactly as requested, that is: short localized day of week, day of month, long localized month, year (four digits), a minus sign with spaces (" - "), hours (24h, two digits), colon (":"), minutes. I don't want seconds, I need an output exactly in this format.
Is there any API for that in Codename One? Any hint? Thank you
Examples of patterns compatible with the Codename One SimpleDateFormat class: https://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
Full implementation example to localize in Italian the date formatted as I requested.
Note that the first day to localize in the weekDays and shortWeekDays arrays is Sunday.
Form hi = new Form("Hi World", BoxLayout.y());
String[] weekDays = {"Domenica", "Lunedì", "Martedì", "Mercoledì", "Giovedì", "Venerdì", "Sabato"};
String[] shortWeekDays = {"Dom", "Lun", "Mar", "Mer", "Gio", "Ven", "Sab"};
String[] months = {"Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre", "Dicembre"};
String[] shortMonths = {"Gen", "Feb", "Mar", "Apr", "Mag", "Giu", "Lug", "Ago", "Set", "Ott", "Nov", "Dic"};
SimpleDateFormat simpleDateFormat = new SimpleDateFormat();
simpleDateFormat.applyPattern("EEE d MMMMMMMMMMMMMMMMMMMM yyyy - HH:mm");
simpleDateFormat.getDateFormatSymbols().setWeekdays(weekDays);
simpleDateFormat.getDateFormatSymbols().setShortWeekdays(shortWeekDays);
simpleDateFormat.getDateFormatSymbols().setMonths(months);
simpleDateFormat.getDateFormatSymbols().setShortMonths(shortMonths);
String date = simpleDateFormat.format(new Date(System.currentTimeMillis()));
hi.add(new Label(date));
hi.show();
Example of output:
Mer 11 Settembre 2019 - 11:51
SimpleDateFormat has localization support by localizing the resource bundle with the following strings:
private static final String L10N_ZONE_LONGNAME = "ZONE_LONGNAME_";
private static final String L10N_ZONE_SHORTNAME = "ZONE_SHORTNAME_";
private static final String L10N_ZONE_LONGNAME_DST = "ZONE_LONGNAME_DST_";
private static final String L10N_ZONE_SHORTNAME_DST = "ZONE_SHORTNAME_DST_";
private static final String L10N_WEEKDAY_LONGNAME = "WEEKDAY_LONGNAME_";
private static final String L10N_WEEKDAY_SHORTNAME = "WEEKDAY_SHORTNAME_";
private static final String L10N_MONTH_LONGNAME = "MONTH_LONGNAME_";
private static final String L10N_MONTH_SHORTNAME = "MONTH_SHORTNAME_";
private static final String L10N_AMPM = "AMPM_";
private static final String L10N_ERA = "ERA_";
So for instance AM/PM can be localized by defining AMPM_AM and AMPM_PM respectively.
You can also use DateFormatSymbols directly but that's a bit painful as you need to do it per SimpleDateFormat instance.
Related
enter image description here I have created a FullCalendar, it is displaying the time in AM/PM. When I am adding the enteries to the calendar, I format the LocalDateTime to 24 hours format but the Calendar displays it in AM/PM format.
How I can display the Calendar entries in 24 hours format?
My Formatter is defined as:
public static final DateTimeFormatter TWENTY_FOUR_HOURS_DATE_TIME_FORMATTER =
DateTimeFormatter.ofPattern("dd-MMM-yyyy HH:mm:ss", AppConstants.APP_LOCALE);
Entry entry = new Entry();
entry.setEditable(false);
entry.setTitle(game.getHomeClub() + " - " +game.getHomeTeam());
Instant now = Instant.now();
String t = LocalDateTime.of(game.getGameTime().toLocalDate(), game.getGameTime().toLocalTime())
.format(FormattingUtils.TWENTY_FOUR_HOURS_DATE_TIME_FORMATTER);
entry.setStart(calendar.getTimezone().convertToUTC(LocalDateTime.parse(t, FormattingUtils.TWENTY_FOUR_HOURS_DATE_TIME_FORMATTER)));
entry.setEnd(game.getGameTime().plus(2, ChronoUnit.HOURS));
calendar = new MyFullCalendar();
calendar.setWeekNumbersVisible(true);
calendar.setNowIndicatorShown(false);
calendar.setNumberClickable(true);
calendar.changeView(CalendarViewImpl.AGENDA_WEEK);
calendar.setLocale(Locale.GERMANY);
private void createTimedEntry(FullCalendar calendar, String title, String start, int minutes, String color) {
Entry entry = new Entry();
setValues(calendar, entry, title, start, minutes, ChronoUnit.MINUTES, color);
calendar.addEntry(entry);
}
You need to set the Locale.
#Route(value = "test")
class TestView extends Composite<Div> {
TestView() {
Locale defaultLocale = Locale.GERMANY
FullCalendar calendar = FullCalendarBuilder.create().build()
calendar.changeView(CalendarViewImpl.TIME_GRID_DAY)
calendar.setSizeFull()
RadioButtonGroup<Locale> localeSwitcher = new RadioButtonGroup()
localeSwitcher.setItems([defaultLocale, Locale.US])
localeSwitcher.addValueChangeListener({ ev ->
calendar.setLocale(localeSwitcher.value)
})
localeSwitcher.setValue(defaultLocale)
VerticalLayout layout = new VerticalLayout(localeSwitcher, calendar)
layout.setSizeFull()
content.add(layout)
}
}
Code (Groovy) above produces following calendar for German Locale:
and this for US Locale:
I know, the question is a bit old, but this answer may help anyone who is still searchting for an answer :)
Regardless of any i18n settings, you may use initial options on the server side to modifiy the event time format.
JsonObject initialOptions = Json.createObject();
JsonObject eventTimeFormat = Json.createObject();
//{ hour: 'numeric', minute: '2-digit', timeZoneName: 'short' }
eventTimeFormat.put("hour", "2-digit");
eventTimeFormat.put("minute", "2-digit");
eventTimeFormat.put("meridiem", false);
eventTimeFormat.put("hour12", false);
initialOptions.put("eventTimeFormat", eventTimeFormat);
FullCalendar calendar = FullCalendarBuilder.create()
.withInitialOptions(defaultInitialOptions)
// ...
.build();
Any initial options you can use you may obtain from the native library docs: https://fullcalendar.io/docs/eventTimeFormat (and other pages)
Consider a text file stored in an online location that looks like this:
;aiu;
[MyEditor45]
Name = MyEditor 4.5
URL = http://www.myeditor.com/download/myeditor.msi
Size = 3023788
Description = This is the latest version of MyEditor
Feature = Support for other file types
Feature1 = Support for different encodings
BugFix = Fix bug with file open
BugFix1 = Fix crash when opening large files
BugFix2 = Fix bug with search in file feature
FilePath = %ProgramFiles%\MyEditor\MyEditor.exe
Version = 4.5
Which details information about a possible update to an application which a user could download. I want to load this into a stream reader, parse it and then build up a list of Features, BugFixes etc to display to the end user in a wpf list box.
I have the following piece of code that essentially gets my text file (first extracting its location from a local ini file and loads it into a streamReader. This at least works although I know that there is no error checking at present, I just want to establish the most efficient way to parse this first. One of these files is unlikely to ever exceed more than about 250 - 400 lines of text.
Dim UpdateUrl As String = GetUrl()
Dim client As New WebClient()
Using myStreamReader As New StreamReader(client.OpenRead($"{UpdateUrl}"))
While Not myStreamReader.EndOfStream
Dim line As String = myStreamReader.ReadLine
If line.Contains("=") Then
Dim p As String() = line.Split(New Char() {"="c})
If p(0).Contains("BugFix") Then
MessageBox.Show($" {p(1)}")
End If
End If
End While
End Using
Specifically I'm looking To collate the information about Features, BugFixes and Enhancements. Whilst I could construct what would in effect be a rather messy if statement I feel sure that there must be a more efficient way to do this , possibly involving linq. I'd welcome any suggestions.
I have added the wpf tag on the off chance that someone reading this with more experience of displaying information in wpf listboxes than I have might just spot a way to effectively define the info I'm after in such a way that it could then be easily displayed in a wpf list box in three sections (Features, Enhancements and BugFixes).
Dom, Here is an answer in C#. I will try to convert it to VB.Net momentarily. First, since the file is small, read all of it into a list of strings. Then select the strings that contain an "=" and parse them into data items that can be used. This code will return a set of data items that you can then display as you like. If you have LinqPad, you can test thecode below, or I have the code here: dotnetfiddle
Here is the VB.Net version: VB.Net dotnetfiddle
Imports System
Imports System.Collections.Generic
Imports System.Linq
Public Class Program
Public Sub Main()
Dim fileContent As List(Of String) = GetFileContent()
Dim dataItems = fileContent.Where(Function(c) c.Contains("=")).[Select](Function(c) GetDataItem(c))
dataItems.Dump()
End Sub
Public Function GetFileContent() As List(Of String)
Dim contentList As New List(Of String)()
contentList.Add("sb.app; aiu;")
contentList.Add("")
contentList.Add("[MyEditor45]")
contentList.Add("Name = MyEditor 4.5")
contentList.Add("URL = http://www.myeditor.com/download/myeditor.msi")
contentList.Add("Size = 3023788")
contentList.Add("Description = This is the latest version of MyEditor")
contentList.Add("Feature = Support for other file types")
contentList.Add("Feature1 = Support for different encodings")
contentList.Add("BugFix = Fix bug with file open")
contentList.Add("BugFix1 = Fix crash when opening large files")
contentList.Add("BugFix2 = Fix bug with search in file feature")
contentList.Add("FilePath = % ProgramFiles %\MyEditor\MyEditor.exe")
contentList.Add("Version = 4.5")
Return contentList
End Function
Public Function GetDataItem(value As String) As DataItem
Dim parts = value.Split("=", 2, StringSplitOptions.None)
Dim dataItem = New DataItem()
dataItem.DataType = parts(0).Trim()
dataItem.Data = parts(1).Trim()
Return dataItem
End Function
End Class
Public Class DataItem
Public DataType As String
Public Data As String
End Class
Or, in C#:
void Main()
{
List<string> fileContent = GetFileContent();
var dataItems = fileContent.Where(c => c.Contains("="))
.Select(c => GetDataItem(c));
dataItems.Dump();
}
public List<string> GetFileContent()
{
List<string> contentList = new List<string>();
contentList.Add("sb.app; aiu;");
contentList.Add("");
contentList.Add("[MyEditor45]");
contentList.Add("Name = MyEditor 4.5");
contentList.Add("URL = http://www.myeditor.com/download/myeditor.msi");
contentList.Add("Size = 3023788");
contentList.Add("Description = This is the latest version of MyEditor");
contentList.Add("Feature = Support for other file types");
contentList.Add("Feature1 = Support for different encodings");
contentList.Add("BugFix = Fix bug with file open");
contentList.Add("BugFix1 = Fix crash when opening large files");
contentList.Add("BugFix2 = Fix bug with search in file feature");
contentList.Add("FilePath = % ProgramFiles %\\MyEditor\\MyEditor.exe");
contentList.Add("Version = 4.5");
return contentList;
}
public DataItem GetDataItem(string value)
{
var parts = value.Split('=');
var dataItem = new DataItem()
{
DataType = parts[0],
Data = parts[1]
};
return dataItem;
}
public class DataItem
{
public string DataType;
public string Data;
}
The given answer only focuses on the first part, converting the data to a structure that can be shaped for display. But I think you main question is how to do the actual shaping.
I used a somewhat different way to collect the file data, using Microsoft.VisualBasic.FileIO.TextFieldParser because I think that makes coding just al little bit easier:
Iterator Function GetTwoItemLines(fileName As String, delimiter As String) _
As IEnumerable(Of Tuple(Of String, String))
Using tfp = New TextFieldParser(fileName)
tfp.TextFieldType = FieldType.Delimited
tfp.Delimiters = {delimiter}
tfp.HasFieldsEnclosedInQuotes = False
tfp.TrimWhiteSpace = False
While Not tfp.EndOfData
Dim arr = tfp.ReadFields()
If arr.Length >= 2 Then
Yield Tuple.Create(arr(0).Trim(), String.Join(delimiter, arr.Skip(1)).Trim())
End If
End While
End Using
End Function
Effectively the same thing happens as in your code, but taking into account Andrew's keen caution about data loss: a line is split by = characters, but the second field of a line consists of all parts after the first part with the delimiter re-inserted: String.Join(delimiter, arr.Skip(1)).Trim().
You can use this function as follows:
Dim fileContent = GetTwoItemLines(file, "=")
For display, I think the best approach (most efficient in terms of lines of code) is to group the lines by their first items, removing the numeric part at the end:
Dim grouping = fileContent.GroupBy(Function(c) c.Item1.TrimEnd("0123456789".ToCharArray())) _
.Where(Function(k) k.Key = "Feature" OrElse k.Key = "BugFix" OrElse k.Key = "Enhancement")
Here's a Linqpad dump (in which I took the liberty to change one item a bit to demonstrate the correct dealing with multiple = characters:
You could do it with Regular Expressions:
Imports System.Text.RegularExpressions
Private Function InfoReader(ByVal sourceText As String) As List(Of Dictionary(Of String, String()))
'1) make array of fragments for each product info
Dim products = Regex.Split(sourceText, "(?=\[\s*\w+\s*])")
'2) declare variables needed ahead
Dim productProperties As Dictionary(Of String, String)
Dim propertyNames As String()
Dim productGroupedProperties As Dictionary(Of String, String())
Dim result As New List(Of Dictionary(Of String, String()))
'2) iterate along fragments
For Each product In products
'3) work only in significant fragments ([Product]...)
If Regex.IsMatch(product, "\A\[\s*\w+\s*]") Then
'4) make array of property lines and extract dictionary of property/description
productProperties = Regex.Split(product, "(?=^\w+\s*=)", RegexOptions.Multiline).Where(
Function(s) s.Contains("="c)
).ToDictionary(
Function(s) Regex.Match(s, "^\w+(?=\s*=)").Value,
Function(s) Regex.Match(s, "(?<==\s+).*(?=\s+)").Value)
'5) extract distinct property names, ignoring numbered repetitions
propertyNames = productProperties.Keys.Select(Function(s) s.TrimEnd("0123456789".ToCharArray)).Distinct.ToArray
'6) make dictionary of distinctProperty/Array(Of String){description, description1, ...}
productGroupedProperties = propertyNames.ToDictionary(
Function(s) s,
Function(s) productProperties.Where(
Function(kvp) kvp.Key.StartsWith(s)
).Select(
Function(kvp) kvp.Value).ToArray)
'7) enlist dictionary to result
result.Add(productGroupedProperties)
End If
Next
Return result
End Function
I have a date String like so :- Fri Oct 31 11:30:58 GMT+05:30 2014
I want to Convert it into 2014-10-31T6:00:00 which should be after adding the offset. How can I do it?
I recommend you do it using the modern date-time API* with the following steps:
Since the given date-time string has a timezone offset value(+05:30), parse it into an OffsetDateTime object using a DateTimeFormatter object created with the applicable pattern.
Convert the obtained OffsetDateTime object into an OffsetDateTime object with ZoneOffset.UTC ensuring that the result is at the same instant. You can do it using OffsetDateTime#withOffsetSameInstant.
The default implementation of OffsetDateTime#toString omits the second and fraction-of-second if they are zero. You can format the OffsetDateTime object, obtained in the last step, using a DateTimeFormatter object created with the applicable pattern.
Your expected output also suggests that you want to ignore the seconds part. If yes, you can do so by using OffsetDateTime#truncatedTo.
Demo:
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String strDateTime = "Fri Oct 31 11:30:58 GMT+05:30 2014";
DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern("E MMM d H:m:s O u", Locale.ENGLISH);
OffsetDateTime odt = OffsetDateTime.parse(strDateTime, dtfInput);
OffsetDateTime odtUtc = odt.withOffsetSameInstant(ZoneOffset.UTC);
DateTimeFormatter dtfOutput = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss", Locale.ENGLISH);
String output = odtUtc.format(dtfOutput);
System.out.println(output);
// In case you want to ignore the seconds
OffsetDateTime odtUtcTruncated = odtUtc.truncatedTo(ChronoUnit.MINUTES);
output = odtUtcTruncated.format(dtfOutput);
System.out.println(output);
}
}
Output:
2014-10-31T06:00:58
2014-10-31T06:00:00
Learn more about the the modern date-time API* from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
First you need a SimpleDateFormat with the pattern that matches your input String: "EEE MMM dd HH:mm:ss z yyyy". Take a look at: SimpleDateFromat API
SimpleDateFormat in = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
Then you can parse the input String to get a corresponding Date object as follows:
Date date = in.parse("Fri Oct 31 11:30:58 GMT+05:30 2014");
Note that Date objects does not have timezone as part of its state. If you want to print the Date in UTC then you need another SimpleDateFormat to format and print the date in your required timezone.
SimpleDateFormat out = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
out.setTimeZone(TimeZone.getTimeZone("UTC"));
out.format(date);
Example: http://ideone.com/Wojec3
public static void main (String[] args) throws java.lang.Exception
{
SimpleDateFormat in = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
SimpleDateFormat out = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
out.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = in.parse("Fri Oct 31 11:30:58 GMT+05:30 2014");
System.out.println(out.format(date));
}
This should do the task, i guess.
public static void main(String args[]) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
format.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(format.format(new Date()));
}
I was wondering if it is possible to make particular days unavailable from the calendar (DatePicker), more specifically every Monday and Tuesday. I have found similar threads (How do create a DatePicker with only Sundays enabled? and Disable specific days of the week on jQuery UI datepicker) about blacking out dates, however, I have not been able to modify their code for my specific goal. I'm writing this application in VB.NET (WPF).
The functions I used so far, for blacking out dates are:
Datepicker1.BlackoutDates.AddDatesInPast()
Datepicker2.BlackoutDates.Add(New CalendarDateRange(DateTime.Now.AddDays(1), DateTime.MaxValue))
Where the first function will blackout the past-dates, and the second will black out all future dates. Because there is a 'DateRange' required for the second function, I'm not able to alter this function for my need.
Thanks in advance
Jerry
I modified one of the examples and came up with this.
It worked for me.
private void MyDatePicker_CalendarOpened(object sender, RoutedEventArgs e)
{
MyDatePicker.DisplayDateStart = DateTime.Now;
MyDatePicker.DisplayDateEnd = DateTime.Now + TimeSpan.FromDays(1000);
var minDate = MyDatePicker.DisplayDateStart ?? DateTime.MinValue;
var maxDate = MyDatePicker.DisplayDateEnd ?? DateTime.MaxValue;
for (var d = minDate; d <= maxDate && DateTime.MaxValue > d; d = d.AddDays(1))
{
if (d.DayOfWeek == DayOfWeek.Monday || d.DayOfWeek == DayOfWeek.Tuesday)
{
MyDatePicker.BlackoutDates.Add(new CalendarDateRange(d));
}
}
}
And here's a bonus: Prevent Certain Dates from Being Selected.
Thank you Okuma Scott, that was some helpful feedback! I rewrote your bit of code to VB language and according to my specific needs.
The included code will check all days in the next year, and will black out all the Mondays and Tuesdays.
Private Sub Datepicker_CalendarOpened(sender As Object, e As RoutedEventArgs) Handles Datepicker.CalendarOpened
Dim currDate As Date = DateTime.Now
Dim maxDate As Date = DateTime.Now.AddDays(356)
While (currDate < maxDate)
If currDate.DayOfWeek = DayOfWeek.Monday Or currDate.DayOfWeek = DayOfWeek.Tuesday Then
DatumSelectie.BlackoutDates.Add(New CalendarDateRange(currDate))
End If
currDate = currDate.AddDays(1)
End While
End Sub
I am new to app-engine Datastore and to NoSQL world in common. I am developing a simple application where a user can declare his/her expenses everyday. Every user(Account) has its own declared expenses. The dash board contains a simple GWT Cell Tree which contains all the years in which the use declared expenses and when he/she clicks on a years, he gets all the months of the years then he clicks on the month and he gets all the days of the month and finally clicking on a day and he gets all the expenses declared in that day. It is something like
*2010
|_ jan
|_1
|_2
|_Food 12d
|_Dress 200d
|_Fun 150d
|_ ...
|_ feb
|_ ...
*2011
|_ jan
|_ feb
|_...
I save expenses entities in the data store for each user(Account) as the account the parent of all the expenses. my expense is as follow:
public class Expense implements Serializable, Comparable {
private String name;
private double price;
private Date date;
public Expense(String name, double price, Date date) {
this.name = name;
this.price = price;
this.date = date;
}
public Expense() {
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
public boolean isPriceValid() {
return price > 0;
}
public void setName(String name) {
this.name = name;
}
public void setPrice(double price) {
this.price = price;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
#Override
public int compareTo(Expense expense) {
if (name.equals(expense.getName())) {
if (date.equals(expense.getDate())) {
return new Double(price).compareTo(expense.getPrice());
}
return date.compareTo(expense.getDate());
}
return name.compareTo(expense.getName());
}
My QUESTION IS: How to query the expenses in the data store and return all different years relater to a specified Account and put them in a list or set or anything else where I can list them ? does I need to fetch all the expenses entities and iterate over them and get all the different years. doesn't sound reasonable. Any advice will be welcome and THANKS IN ADVANCE.
Several comments related to your post :
--> I wouldn't store a financial amount as a Double. Going that route will lead you to big problems with rounding errors. There are a lot of posts on this one. I would suggest you to store it as "DollarCent" and declare it as an integer. You simply multiply the amount by 100 when you store it and when displaying it you divide by 100.
--> Why do you declare your entity in the Datastore as implementing Serializable ? I would store without Serializable.
--> Related to the specific question on displaying the data by year, reading your question I see no other way than fetching the data. What I would do is ask GAE to order the data to avoid having to order it afterwards. Using Objectify, it would simply be q.filter(...).order(-date).order(amount).
Hope this helps !
Hugues