使用momentjs检测无效时区

时间:2018-01-25 02:34:11

标签: javascript datetime timezone momentjs

有没有办法用momentjs检测出无效的时区? 如果我这样做:

isValid()

有没有办法让false返回Moment Timezone has no data for invalid timezone. See http://momentjs.com/timezone/docs/#/data-loading/,还是有其他方法可以检测到时区无效?

它记录以下内容:StringBuffer finalString = new StringBuffer(); try { BufferedReader br = new BufferedReader(new FileReader("collegeData 2.txt")); StringBuffer returnFile = new StringBuffer(); returnFile.append(br.readLine() + br.readLine()); ArrayList<String> allData = new ArrayList<String>(); boolean completedFirstSection = false; int count = 2; String addString = ""; String nextLine; while ((nextLine=br.readLine())!=null) { if(count < 990) { addString += nextLine; count++; } else { String sub = nextLine.substring(16); sub = sub.substring(0, sub.length()); addString = sub + ":{" + nextLine + "," + addString.substring(0, addString.length()-2) + br.readLine(); br.readLine(); allData.add(addString); count = 2; } } allData.add("}}]"); System.out.println("here"); System.out.println(returnFile.toString()); finalString = returnFile; br.close(); } catch (IOException e) { e.printStackTrace(); } 但是我如何以编程方式进行说明?

2 个答案:

答案 0 :(得分:2)

检查是否m.tz() === undefined

&#13;
&#13;
let m = moment.tz("01/01/2019 5:30pm", "MM/DD/YYYY h:mma", true, "invalid timezone");
console.log(`"invalid timezone" results in .tz() == ${m.tz()}`)

m = moment.tz("01/01/2019 5:30pm", "MM/DD/YYYY h:mma", true, "Australia/Melbourne");
console.log(`"Australia/Melbourne" results in .tz() == ${m.tz()}`)
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.14/moment-timezone-with-data.min.js"></script>
&#13;
&#13;
&#13;

当然,您还可以检查区域是否存在

&#13;
&#13;
console.log(`"invalid zone name is ${moment.tz.zone("invalid zone name")}`);
console.log(`"australia/nsw" is ${JSON.stringify(moment.tz.zone("australia/nsw"), null, 4)}`);
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.14/moment-timezone-with-data.min.js"></script>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

如果你正在使用一个完全创建的Moment对象,那么Jaromanda X给出的答案是可行的方法。但是,如果您只是测试时区名称是否有效(并加载到时刻),那么您不需要构造Moment对象来执行此操作。只需测试时区名称本身。

if (!moment.tz.zone('FooBarTimeZone')) {
    console.log('Invalid time zone');
} else {
     console.log('Valid time zone');
}

请注意,这是有效的,因为moment.tz.zone函数返回Zone对象(类似于任何对象是真实的)或null(这是假的) )。

另请注意,最初有一个moment.tz.zoneExists函数,它仍然可以正常工作 - 但现在会给出一个弃用消息,描述使用上述技术。