解析字符串到日期错误

时间:2017-02-24 18:32:02

标签: java date time timer

为什么这不起作用?我正在使用SimpleDateFormat解析String,但这会在try {}内的行上产生错误。

String timerDate = "28 05:24:50"; // timer will stop when reached this date

public String getTimer() {
    SimpleDateFormat format = new SimpleDateFormat("dd HH:mm:ss");

    Date currentDate = Calendar.getInstance().getTime();
    Date stopDate = null;
    try {
        stopDate = format.parse(timerDate);
    } catch (ParseException e) {
        e.printStackTrace();
        return "";
    }

(有更多代码继续进行,但它无关紧要。它无法解析。

异常消息:

java.lang.NullPointerException
    at java.text.SimpleDateFormat.parse(Unknown Source) ~[?:1.8.0_121]
    at java.text.DateFormat.parse(Unknown Source) ~[?:1.8.0_121]
    at com.thefuzzyhead.octopia.util.general.MOTDManager.getTimer(MOTDManager.java:98) ~[?:?]
    at com.thefuzzyhead.octopia.util.general.MOTDManager.<init>(MOTDManager.java:22) ~[?:?]
    at com.thefuzzyhead.octopia.Main.onEnable(Main.java:37) ~[?:?]
    at org.bukkit.plugin.java.JavaPlugin.setEnabled(JavaPlugin.java:321) ~[spigot-1.8.jar:git-Spigot-eb87f2b-ee6d0fa]
    at org.bukkit.plugin.java.JavaPluginLoader.enablePlugin(JavaPluginLoader.java:335) [spigot-1.8.jar:git-Spigot-eb87f2b-ee6d0fa]
    at org.bukkit.plugin.SimplePluginManager.enablePlugin(SimplePluginManager.java:405) [spigot-1.8.jar:git-Spigot-eb87f2b-ee6d0fa]
    at org.bukkit.craftbukkit.v1_8_R1.CraftServer.loadPlugin(CraftServer.java:356) [spigot-1.8.jar:git-Spigot-eb87f2b-ee6d0fa]
    at org.bukkit.craftbukkit.v1_8_R1.CraftServer.enablePlugins(CraftServer.java:316) [spigot-1.8.jar:git-Spigot-eb87f2b-ee6d0fa]
    at net.minecraft.server.v1_8_R1.MinecraftServer.q(MinecraftServer.java:402) [spigot-1.8.jar:git-Spigot-eb87f2b-ee6d0fa]
    at net.minecraft.server.v1_8_R1.MinecraftServer.k(MinecraftServer.java:370) [spigot-1.8.jar:git-Spigot-eb87f2b-ee6d0fa]
    at net.minecraft.server.v1_8_R1.MinecraftServer.a(MinecraftServer.java:325) [spigot-1.8.jar:git-Spigot-eb87f2b-ee6d0fa]
    at net.minecraft.server.v1_8_R1.DedicatedServer.init(DedicatedServer.java:211) [spigot-1.8.jar:git-Spigot-eb87f2b-ee6d0fa]
    at net.minecraft.server.v1_8_R1.MinecraftServer.run(MinecraftServer.java:505) [spigot-1.8.jar:git-Spigot-eb87f2b-ee6d0fa]
    at java.lang.Thread.run(Unknown Source) [?:1.8.0_121]

1 个答案:

答案 0 :(得分:0)

您的问题是在调用timerDate之前尚未设置parse()

确保在解析之前初始化timerDate,或者防止它为空。