前段时间认真的学习了一下openharmony。慢慢的入门,今天把结事定时器来做一个日历+时钟。
1、新建工程低代码工程,创建两个Text控件:
2、创建变量,用于存放日期、时钟
@State strTime: string = '00:00:00'
@State strDate: string = '2022-10-17'
@State day:number = 0
@State month:number = 0
@State year:number = 0
@State hours: number = 0
@State minutes: number = 0
@State seconds: number = 0
@State interval: number = 0
3、建立一个函数用于定时更新日期与时间。
timeChange(){
var that = this
that.interval =setInterval(function () {
let current = new Date()
that.seconds = current.getSeconds()
that.hours = current.getHours()
that.minutes = current.getMinutes()
that.year = current.getFullYear()
that.month = current.getMonth() +1
that.day = current.getUTCDate()
that.strDate = that.year.toString() + '年' + that.month.toString() + '月' + that.day.toString() + '日'
if (that.hours<10)
{
that.strTime = '0' + that.hours.toString()
}
else
{
that.strTime = that.hours.toString()
}
if (that.minutes<10){
that.strTime = that.strTime + ':' + '0' + that.minutes.toString()
}
else
{
that.strTime = that.strTime + ':' + that.minutes.toString()
}
if (that.seconds<10){
that.strTime = that.strTime + ':' + '0' + that.seconds.toString()
}
else
{
that.strTime = that.strTime + ':' + that.seconds.toString()
}
}, 1000)
}
4、标签绑定变量日期绑定strDate,时钟绑定strTime:
下载后就可以看到日期、时钟了:
index.ets函数代码如下:
@Entry
@Component
struct Index {
@State strTime: string = '00:00:00'
@State strDate: string = '2022-10-17'
@State day:number = 0
@State month:number = 0
@State year:number = 0
@State hours: number = 0
@State minutes: number = 0
@State seconds: number = 0
@State interval: number = 0
build() {
}
timeChange(){
var that = this
that.interval =setInterval(function () {
let current = new Date()
that.seconds = current.getSeconds()
that.hours = current.getHours()
that.minutes = current.getMinutes()
that.year = current.getFullYear()
that.month = current.getMonth() +1
that.day = current.getUTCDate()
that.strDate = that.year.toString() + '年' + that.month.toString() + '月' + that.day.toString() + '日'
if (that.hours<10)
{
that.strTime = '0' + that.hours.toString()
}
else
{
that.strTime = that.hours.toString()
}
if (that.minutes<10){
that.strTime = that.strTime + ':' + '0' + that.minutes.toString()
}
else
{
that.strTime = that.strTime + ':' + that.minutes.toString()
}
if (that.seconds<10){
that.strTime = that.strTime + ':' + '0' + that.seconds.toString()
}
else
{
that.strTime = that.strTime + ':' + that.seconds.toString()
}
}, 1000)
}
onPageShow(){
this.timeChange()
}
}
【总结】这个实验主要用到定时器、日期函数。还有就是开机启动的onPageShow函数。
【感想】经达这段时间的学习与实践,感openHarmony真的是强大,而且入门也是容易的,最近的教材也越为越多了。
日历时钟
|