如何将LocalDate格式化为用户所在位置的标准格式?

时间:2018-10-05 20:15:37

标签: java localization formatting date-formatting localdate

如何根据用户所在位置的格式来格式化using System; using System.Collections.Generic; public class Program { public class Weather{ public Weather(Dictionary<int,int> highTemps,Dictionary<int,int> lowTemps,Dictionary<int,int> tempRange){ HighTemps = highTemps; LowTemps = lowTemps; } public Dictionary<int,int> HighTemps {get;set;} public Dictionary<int,int> LowTemps {get;set;} public Dictionary<int,int> TempRange{ get{ Dictionary<int,int> result = new Dictionary<int,int>(); foreach (KeyValuePair<int, int> pair in HighTemps) { result.Add(pair.Key,pair.Value - LowTemps[pair.Key]); } return result; } } } public static void Main(){ Weather temps = new Weather(new Dictionary<int,int>(),new Dictionary<int,int>(),new Dictionary<int,int>()); //add day of week and temp temps.HighTemps.Add(1, 84); temps.HighTemps.Add(2, 86); temps.HighTemps.Add(3, 81); temps.HighTemps.Add(4, 82); temps.HighTemps.Add(5, 82); temps.HighTemps.Add(6, 83); temps.HighTemps.Add(7, 84); temps.LowTemps.Add(1, 65); temps.LowTemps.Add(2, 66); temps.LowTemps.Add(3, 71); temps.LowTemps.Add(4, 60); temps.LowTemps.Add(5, 64); temps.LowTemps.Add(6, 69); temps.LowTemps.Add(7, 70); foreach (KeyValuePair<int, int> pair in temps.TempRange) { Console.WriteLine("The range for Day {0} of the week was {1}", pair.Key, pair.Value); } } } //Output: The range for Day 1 of the week was 19 The range for Day 2 of the week was 20 The range for Day 3 of the week was 10 The range for Day 4 of the week was 22 The range for Day 5 of the week was 18 The range for Day 6 of the week was 14 The range for Day 7 of the week was 14 。我希望美国人民看到“ 6/28/2018”,而欧洲人民看到“ 28/6/2018”,中国人民看到“ 2018/6/28”。

我需要使用LocalDate还是我需要使用其他东西?

我还需要根据用户所在位置的标准将字符串转换为DateTimeFormatter formatter = ...

1 个答案:

答案 0 :(得分:4)

一种方法是使用DateTimeFormatter.ofLocalizedDate()工厂方法,该方法为ISO年表返回特定于语言环境的日期格式。

DateTimeFormatter fmt = DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL);
LocalDate now = LocalDate.now(); // 2018-10-05
String txt = fmt.format(now); // Friday, 5 October 2018
LocalDate d = LocalDate.parse(txt, fmt); // 2018-10-05