有没有办法用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();
}
但是我如何以编程方式进行说明?
答案 0 :(得分:2)
检查是否m.tz() === undefined
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;
当然,您还可以检查区域是否存在
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;
答案 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
函数,它仍然可以正常工作 - 但现在会给出一个弃用消息,描述使用上述技术。