当前位置: 首页 > 知识库问答 >
问题:

使用字符串将日期从数字格式转换/替换为EEEE、MMMMDD、yyyy格式

宁卓
2023-03-14
// format output EEEE, MM dd yyyy 
SimpleDateFormat write      = new SimpleDateFormat("EEEE, MMMM dd, yyyy");
SimpleDateFormat read       = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat readYy     = new SimpleDateFormat("MM/dd/yy");
SimpleDateFormat writeYyyy  = new SimpleDateFormat("MM/dd/yyyy");

// dates used for a test conversion     
String[] dates = {
"7/20/1969","7/4/2012",
"9/11/01",      // this should be 2001 (m/d/yyyy = 8 chars, mm/dd/yy = 8 chars
"02/29/1975", "6/11/1956", "31/31/00", "7/&&/88" }

现在我一直在试图找到一个应该可行的解决办法,但由于某种原因,它并不奏效。请参阅下一段代码:

String line = "We landed on the moon on 7/20/1969. 7/4/2012 is the Fourth of July.";

// I expect to see "7/20/1969" and "7/20/2012" as output but the following does not
// work:

dateRegex = "^([1-9]|0[1-9]|1[012])/([1-9]|0[1-9]|[1-2][0-9]|3[01])/(\\d\\d)|(19|20)\\d\\d$";
Pattern p = Pattern.compile(dateRegex);
Matcher m = p.matcher(line);
System.out.println(line);

while(m.find()) {
    System.out.println("Found " + p + " at: " + m.start());
    // return the sequences characters matching "dateRegex (or so it should...?)
    System.out.println("Match : " + m.group())  // it does not print 'cause nothing is found
}
// the above code works find with a simpler regex string variable, but nothing like this
// what's worng here?   Is this a wrong "dateRegex" pattern?  Thanks.

我会很感激任何能证明结果的帮助。多谢了。

共有1个答案

柴霖
2023-03-14

是否使用String.Format()?

String.format("On %s, a really cool thing happened.", DateTimeFormatter.print()DateTime.now());

当然,这个例子使用了卓越得多的Joda时间库。你也该这么做。

更新:在正确理解问题之后(我认为),这个小示例,使用标准Java库应该可以让您开始。

package com.company;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;

public class Main {

    public static void main(String[] args) {
        String example = "On 9/6/78, a really cool thing happened...";
        SimpleDateFormat replacement = new SimpleDateFormat("EEEE, MMMM dd, yyyy");
        Pattern datePattern = Pattern.compile("\\b\\w{1,2}/\\w{1,2}/(?:\\w{4}|\\w{2})\\b");
        Date now = new Date();
        System.out.println(datePattern.matcher(example).replaceAll(replacement.format(now)));
    }
}
 类似资料:
  • 问题内容: 我想要这种格式 问题答案: 您需要先 解析 日期字符串(使用方法),才能 使用与格式匹配的格式获取对象。 然后使用所需的格式来 格式化 Date对象(Use 方法)以获取字符串。 输出:- 第一种格式是RFC 822 TimeZone与您的日期字符串匹配。有关在日期格式中使用的其他各种选项,请参见。

  • 问题内容: 我在网络上阅读了更多问题,但还没有找到解决方案。 我有一个完全像这种格式的 字符串, 例如“ 14/05/1994”。 我需要以 相同的格式* 将其隐藏到 java.util.Date 中。 * 我试过了: 但结果是:1994年5月14日星期六星期六00:00:00 结果是:1994年5月14日不是字符串,而是java.util.Date? 问题答案: 一个不 具有 的格式。这只是个约

  • 我得到一串零。有人能帮忙吗?

  • 我在presto上,把日期格式化为varchar,看起来像- 我如何转换这个?

  • 问题内容: 我有一个包含日期格式的字符串。 您如何建议我以最佳方式将其转换为格式? 这就是我天真地做的事情: 但是还有其他更优雅,更有效的方法吗?就是 使用一些内置功能?快速搜寻API时,我找不到一个。 这里有人知道替代方法吗? 问题答案: 用途:

  • 我有这段代码,在这里我试图将日期字符串从一种格式转换为另一种格式,最后我想再次使用日期对象。