将日期字符串转换为整数数组。

huangapple go评论156阅读模式
英文:

convert Date string to array of integers

问题

我有一个格式为:"YYYY-MM-DD"的字符串,我想将它转换为整数数组。

这是我的代码:

int year, month, day;
Date date = Calendar.getInstance().getTime();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String strDate = dateFormat.format(date);

例如,如果日期是2017-03-16,我希望我的数组如下:[2017, 3, 16]。

英文:

I have a string in the format: "YYYY-MM-DD" and I want to convert it into an array of integer

this is my code :

int year, month, day;
Date date = Calendar.getInstance().getTime();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String strDate = dateFormat.format(date);

for example, if the date is 2017-03-16 I want my array be like [2017,3,16].

答案1

得分: 4

首先,我建议使用 java-time API 中的 LocalDateDateTimeFormatter,停止使用CalendarSimpleDateFormat这些过时的日期类。

LocalDate currentDate = LocalDate.now();
String dateString = currentDate.format(DateTimeFormatter.ISO_DATE);

如果你想将日期字符串转换为整数数组,可以基于 - 进行拆分。

Integer[] array = 
    Arrays
    .stream(dateString.split("-"))
    .map(Integer::valueOf)
    .toArray(Integer[]::new);
英文:

Firstly i would say to use LocalDate, DateTimeFormatter from java-time API and stop usingCalendar and SimpleDateFormat legacy date class

LocalDate currentDate = LocalDate.now();
String dateString = currentDate.format(DateTimeFormatter.ISO_DATE);

If you want to convert date string to int array, then split is based on -.

Integer[] array = 
    Arrays
    .stream( dateString.split("-") )
    .map( Integer::valueOf )
    .toArray( Integer[]::new )
;

答案2

得分: 1

这在您的所有日期都按照您问题中描述的方式进行预格式化的情况下是有意义的。但是,如果您正在使用日期对象,我建议利用Java 8+的功能。

首先,定义一个lambda来提取日期的各个部分并返回一个数组。请注意,您可以添加其他日期组件或轻松更改数组中的顺序。

    Function<LocalDate, int[]> getParts =
            ld -> new int[] { ld.getDayOfMonth(),
                    ld.getMonthValue(), ld.getYear() };

然后您可以这样应用它。

    LocalDate d = LocalDate.of(2020, 3, 15);
    int[] parts = getParts.apply(d);
    System.out.println(Arrays.toString(parts));

输出

[15, 3, 2020]

或者这样

    // 创建一个 LocalDate 对象的列表。
    List<LocalDate> localDates = List.of(
    LocalDate.of(2020, 3, 15), LocalDate.of(2020, 3, 16));
    // 并转换为日期属性数组的列表。
    List<int[]> dates = localDates.stream().map(getParts::apply)
              .collect(Collectors.toList());
    dates.forEach(a->System.out.println(Arrays.toString(a)));

输出

[15, 3, 2020]
[16, 3, 2020]

这种方法的另一个优点是,您无需确保日期之间的格式相同。

英文:

This makes sense if all of your dates were preformatted as described in your question. But if you are using date Objects I would take advantage of the Java 8+ capabilities.

First, define a lambda to extract the parts and return an array. Note that you can add other date components or easily change the order in the array.

	    Function&lt;LocalDate, int[]&gt; getParts =
				ld -&gt; new int[] { ld.getDayOfMonth(),
						ld.getMonthValue(), ld.getYear() };

Then you can apply it like so.

		LocalDate d = LocalDate.of(2020, 3, 15);
		int[] parts = getParts.apply(d);
        System.out.println(Arrays.toString(parts));

Prints

[15, 3, 2020]

Or this

        // create a list of LocalDate objects.
        List&lt;LocalDate&gt; localDates = List.of(
		LocalDate.of(2020, 3, 15), LocalDate.of(2020, 3, 16));
        // and convert to a list of arrays of date attributes.
        List&lt;int[]&gt; dates = localDates.stream().map(getParts::apply)
				  .collect(Collectors.toList());
		dates.forEach(a-&gt;System.out.println(Arrays.toString(a)));

Prints

[15, 3, 2020]
[16, 3, 2020]

Another advantage of this is that you don't have to ensure the format is the same from date to date.

答案3

得分: 0

很快且简单。如果你必须使用一个数组,解决方案如下:

导入以下内容:

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

然后在你的主方法或其他方法中:

int[] dateArray = new int[100]; // 或者你想要的大小

Date date = Calendar.getInstance().getTime();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String strDate = dateFormat.format(date);

String[] line = strDate.split("-");
        
for (int i = 0; i < line.length; i++)
{
    dateArray[i] = Integer.parseInt(line[i]);
}

就应该可以了。

英文:

It's very quick and easy. If you are bound to use an array, the solution =>
import these=>

    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    import java.util.Date;

then in your main or other method =>

    int[] dateArray = new int[100]; // or your desired size
	
	Date date = Calendar.getInstance().getTime();
	DateFormat dateFormat = new SimpleDateFormat(&quot;yyyy-MM-dd&quot;);
	String strDate = dateFormat.format(date);
	
	String[] line = strDate.split(&quot;-&quot;);
	
	for (int i = 0; i &lt; line.length; i++)
	{
		dateArray[i] = Integer.parseInt(line[i]);
	}

should do it.

huangapple
  • 本文由 发表于 2020年3月16日 06:32:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/60698332.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定