在低版本cesium中,将时间轴转换为中文一般做法是:
1.定义方法,将cesium时间进行转换
function DateTimeFormatter(datetime, viewModel, ignoredate) {
let julianDT = new Cesium.JulianDate();
Cesium.JulianDate.addHours(datetime, 0, julianDT);
let gregorianDT = Cesium.JulianDate.toGregorianDate(julianDT);
let objDT;
if (ignoredate) objDT = "";
else {
gregorianDT.month == 1
? (objDT = new Date(gregorianDT.year, gregorianDT.month, gregorianDT.day))
: (objDT = new Date(gregorianDT.year, gregorianDT.month - 1, gregorianDT.day));
objDT =
gregorianDT.year +
"年" +
objDT.toLocaleDateString("zh-cn", { month: "short" }) +
gregorianDT.day +
"日";
if (viewModel || gregorianDT.hour + gregorianDT.minute === 0) return objDT;
objDT += " ";
}
return (
objDT +
Cesium.sprintf("%02d:%02d:%02d", gregorianDT.hour, gregorianDT.minute, gregorianDT.second)
);
}
function TimeFormatter(time, viewModel) {
return DateTimeFormatter(time, viewModel, true);
}
2.在初始化视图时进行调用
viewer.animation.viewModel.dateFormatter = DateTimeFormatter;
viewer.animation.viewModel.timeFormatter = TimeFormatter;
viewer.timeline.makeLabel = DateTimeFormatter;
但是以上方式在版本稍微高一点的cesium里,会报“sprintf is not a function”; 盲猜是已经没有这个函数了。
在高版本里,我的写法是:
// cesium时钟时间格式化函数
function CesiumTimeFormatter(datetime) {
var julianDT = new Cesium.JulianDate();
Cesium.JulianDate.addHours(datetime, 8, julianDT);
var gregorianDT = Cesium.JulianDate.toGregorianDate(julianDT);
let hour = gregorianDT.hour + "";
let minute = gregorianDT.minute + "";
let second = gregorianDT.second + "";
return `${hour.padStart(2, "0")}:${minute.padStart(2, "0")}:${second.padStart(2, "0")}`;
}
// cesium时钟日期格式化函数
function CesiumDateFormatter(datetime) {
var julianDT = new Cesium.JulianDate();
Cesium.JulianDate.addHours(datetime, 8, julianDT);
var gregorianDT = Cesium.JulianDate.toGregorianDate(julianDT);
let month = gregorianDT.month + "";
let day = gregorianDT.day + "";
return `${gregorianDT.year}年${month.padStart(2, "0")}月${day.padStart(2, "0")}日`;
}
// cesium时间轴格式化函数
function CesiumDateTimeFormatter(datetime) {
var julianDT = new Cesium.JulianDate();
Cesium.JulianDate.addHours(datetime, 8, julianDT);
let gregorianDT = Cesium.JulianDate.toGregorianDate(julianDT);
let year = gregorianDT.year + "";
let month = gregorianDT.month + "";
let day = gregorianDT.day + "";
let hour = gregorianDT.hour + "";
let minute = gregorianDT.minute + "";
let seconds = gregorianDT.second + "";
return `${year}年${month.padStart(2, "0")}月${day.padStart(2, "0")}日 ${hour.padStart(2, "0")}:${minute.padStart(2, "0")}:${seconds.padStart(2, "0")}`;
}
在初始化时依旧对这些方法进行调用:
viewer.animation.viewModel.timeFormatter = CesiumTimeFormatter;
viewer.timeline.makeLabel = CesiumDateTimeFormatter;
viewer.animation.viewModel.dateFormatter = CesiumDateFormatter;
可以去试一波,我的版本是1.114.0 与1.95.0版本都测试过。
具体样式为: