Use Calendar

本文提供了将日期类型转换为字符串以及从字符串还原为日期的方法。重点介绍了如何处理年月日的格式化,特别注意月份的加减1操作以确保时间的一致性。
转换日期类型为字符串: 
public static String calendarToYMD(Calendar inDate){
     StringBuffer ret = new StringBuffer (8);
     ret.append (inDate.get(Calendar.YEAR));
     if ( inDate.get(Calendar.MONTH)+1<10)
       ret.append('0');
     ret.append ((inDate.get(Calendar.MONTH)+1));
     if (inDate.get(Calendar.DAY_OF_MONTH)<10)
       ret.append ('0');
     ret.append(inDate.get(Calendar.DAY_OF_MONTH));
     return ret.toString();
  }
转换字符串为日期类型:
  public static Calendar YMDToCalendar(String inDate)
      throws Exception{
     Calendar ret = Calendar.getInstance();
     if (inDate.length() < 8)
         throw new Exception ( "Invalid date format '" + inDate + "'" );
     int year = Integer.parseInt(inDate.substring(0,4));
     int month = Integer.parseInt(inDate.substring ( 4, 6 ) );
     int day = Integer.parseInt(inDate.substring ( 6, 8 ) );

     if (day<1||day>31||month<1||month>12)
          throw new Exception ( "Invalid date '" + inDate + "'");

     if (inDate.length()>8 ) {
       if (inDate.charAt(8) == 'T'){
          try {
             int hour = Integer.parseInt ( inDate.substring ( 9, 11 ) );
             int minute = Integer.parseInt ( inDate.substring ( 11, 13 ) );
             int second = Integer.parseInt ( inDate.substring ( 13, 15 ) );
             ret.set ( year, month-1, day, hour, minute, second );//TODO
         } catch ( NumberFormatException nef ) {
             throw new Exception ( "Invalid time in date string '" +inDate+"'");
         }
       } else {

            throw new Exception ( "Invalid date format '" + inDate+"'");
       }
     } else {
        ret.set(year, month-1, day);
     }
     return ret;
   }
在上述的转换过程中需要注意的一个问题是,如果我们把日期转化为了字符串则,MONTH信息需要在初始值的基础上+1
而在相反的过程中,我们则需要-1,只有这样处理后我们在使用cal.getTime()方法返回的时间才能和经过转化的String
对象对应上。
<!DOCTYPE html> <html lang="zh" class="van-theme-light"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>每天按时喝水养生</title> <!-- 引入 Vant CSS --> <link rel="stylesheet" href="assets/index.css"> <style> body { margin: 0; padding: 0; background: #f5f7fa; font-family: -apple-system, BlinkMacSystemFont, "Helvetica Neue", Helvetica, Segoe UI, Arial, Roboto, "PingFang SC", "miui", "Hiragino Sans GB", "Microsoft Yahei", sans-serif; } #app { max-width: 480px; margin: 0 auto; background: white; min-height: 100vh; box-shadow: 0 0 20px rgba(0,0,0,0.05); } .divbox { margin: 10px; } .flexbox { display: flex; flex-wrap: wrap; justify-content: center; gap: 10px; margin: 20px 0; } .water-progress { background: white; border-radius: 12px; padding: 20px; margin: 20px 0; box-shadow: 0 2px 12px rgba(0,0,0,0.05); } .progress-bar { height: 20px; background: #ebedf0; border-radius: 10px; overflow: hidden; margin-top: 15px; position: relative; } .progress-fill { height: 100%; background: linear-gradient(to right, #07c160, #1baeae); border-radius: 10px; transition: width 0.5s ease; } .progress-text { position: absolute; top: 0; left: 0; width: 100%; height: 100%; display: flex; justify-content: center; align-items: center; font-size: 12px; color: #333; font-weight: bold; } .water-cards { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; margin-top: 20px; } .water-card { background: white; border-radius: 8px; padding: 15px; text-align: center; box-shadow: 0 2px 8px rgba(0,0,0,0.05); transition: all 0.3s ease; cursor: pointer; } .water-card.active { background: #e6f7ff; transform: scale(1.05); box-shadow: 0 4px 12px rgba(24, 144, 255, 0.2); } .water-card:hover { transform: translateY(-3px); } .water-card h3 { margin: 0 0 10px 0; font-size: 16px; color: #333; } .water-card p { margin: 0; color: #666; font-size: 14px; } /* 动画效果 */ @keyframes pulse { 0% { transform: scale(1); } 50% { transform: scale(1.05); } 100% { transform: scale(1); } } .pulse { animation: pulse 2s infinite; } .water-btn { width: 100%; margin-top: 25px; border-radius: 8px; font-weight: bold; letter-spacing: 1px; height: 50px; font-size: 16px; } .statistics { display: flex; justify-content: space-around; margin: 25px 0; text-align: center; } .stat-item { flex: 1; } .stat-value { font-size: 24px; font-weight: bold; color: #07c160; } .stat-label { font-size: 12px; color: #969799; margin-top: 5px; } .reminder { background: #fff7e6; border-left: 4px solid #ffa940; padding: 10px 15px; border-radius: 0 8px 8px 0; margin: 15px 0; } .tips { background: #f0f7ff; border-radius: 8px; padding: 15px; margin-top: 20px; } .tips h3 { margin-top: 0; color: #1890ff; } .tips ul { padding-left: 20px; margin-bottom: 0; } .tips li { margin-bottom: 8px; } .nav-btn { width: 40px; height: 40px; border-radius: 50%; display: flex; justify-content: center; align-items: center; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); transition: all 0.3s ease; } .nav-btn:hover { background: #f0f0f0; transform: scale(1.1); } .date-btn { font-size: 16px; font-weight: bold; padding: 0 20px; height: 40px; line-height: 40px; border-radius: 20px; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); transition: all 0.3s ease; } .date-btn:hover { background: #f0f0f0; transform: scale(1.05); } van-popup { z-index: 9999 !important; border: 1px solid red; /* 调试用 */ } van-calendar { border: 2px solid green !important; /* 调试用 */ } </style> </head> <body> <div id="app"> <!-- 导航栏 --> <van-nav-bar title="每天按时喝水养生" left-arrow @click-left="goBack" fixed> <template #right> <van-icon name="wap-home-o" size="24" /> </template> </van-nav-bar> <!-- 主要内容 --> <div style="padding-top: 46px;"> <div class="divbox"> <div class="flexbox"> <van-button icon="arrow-left" plain type="primary" class="nav-btn" @click="prevDay" ></van-button> <van-button plain type="primary" class="date-btn" @click="showCalendar" > {{ formattedDate }} </van-button> <van-button icon="arrow-right" plain type="primary" class="nav-btn" @click="nextDay" ></van-button> </div> <div class="water-progress"> <h3>今日喝水进度</h3> <div class="progress-bar"> <div class="progress-fill" :style="{ width: progressPercentage }"></div> <div class="progress-text">{{ waterIntake }}ml / {{ target }}ml</div> </div> <div class="statistics"> <div class="stat-item"> <div class="stat-value">{{ completed }}</div> <div class="stat-label">已完成</div> </div> <div class="stat-item"> <div class="stat-value">{{ remaining }}</div> <div class="stat-label">剩余</div> </div> <div class="stat-item"> <div class="stat-value">8</div> <div class="stat-label">建议次数</div> </div> </div> </div> <div class="reminder"> <van-icon name="warning-o" color="#ffa940" /> 您今天还有 {{ remaining }} 杯水需要饮用 </div> <h3>选择饮水量</h3> <div class="water-cards"> <div v-for="(size, index) in cupSizes" :key="index" class="water-card" :class="{ active: selectedSize === size }" @click="selectSize(size)" > <h3>{{ size }}ml</h3> <p>{{ getCupDescription(size) }}</p> </div> </div> <van-button type="primary" class="water-btn" @click="addWater" :disabled="waterIntake >= target" > <van-icon name="water-o" size="18" /> 记录喝水 {{ selectedSize }}ml </van-button> <div class="tips"> <h3>健康饮水小贴士</h3> <ul> <li>早晨起床后喝一杯温水,帮助清理肠胃</li> <li>不要等到口渴才喝水,定时补充水分</li> <li>运动前后需要额外补充水分</li> <li>少量多次饮水比一次性大量饮水更健康</li> </ul> </div> </div> </div> <!-- 日期选择弹窗 --> <van-popup v-model:show="calendarVisible" position="bottom" round> <van-calendar :default-date="currentDate" :show-confirm="true" @confirm="onDateConfirm" /> </van-popup> </div> <!-- Vue 3 & Vant 3 --> <script src="assets/vue.global.prod.js"></script> <script src="assets/vant.min.js"></script> <script> const { createApp } = Vue; const app = createApp({ data() { return { currentDate: new Date(), calendarVisible: false, waterIntake: 600, target: 2000, cupSizes: [100, 200, 300], selectedSize: 200 }; }, computed: { formattedDate() { const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']; const y = this.currentDate.getFullYear(); const m = String(this.currentDate.getMonth() + 1).padStart(2, '0'); const d = String(this.currentDate.getDate()).padStart(2, '0'); const w = weekdays[this.currentDate.getDay()]; return `${y}/${m}/${d}(${w})`; }, progressPercentage() { const percentage = Math.min(100, (this.waterIntake / this.target) * 100); return `${percentage}%`; }, completed() { return Math.ceil(this.waterIntake / 250); }, remaining() { return Math.max(0, Math.ceil((this.target - this.waterIntake) / 250)); } }, methods: { showCalendar() { this.calendarVisible = true; }, onDateConfirm(date) { console.log('选择的日期:', date); this.currentDate = date; this.calendarVisible = false; }, prevDay() { const newDate = new Date(this.currentDate); newDate.setDate(newDate.getDate() - 1); this.currentDate = newDate; }, nextDay() { const newDate = new Date(this.currentDate); newDate.setDate(newDate.getDate() + 1); this.currentDate = newDate; }, selectSize(size) { this.selectedSize = size; }, addWater() { if (this.waterIntake + this.selectedSize <= this.target) { this.waterIntake += this.selectedSize; vant.Notify({ type: 'success', message: `成功记录 ${this.selectedSize}ml 饮水`, duration: 1000 }); } else { vant.Dialog.alert({ title: '提示', message: '您已达到今日饮水目标!' }); } }, getCupDescription(size) { return { 100: '小杯', 200: '标准杯', 300: '大杯' }[size] || '自定义'; }, goBack() { history.back(); } } }); // ✅ 只需这一句即可注册全部 Vant 组件 app.use(vant); // 🔁 不需要再单独 use Calendar 或 Popup app.mount('#app'); </script> </body> </html> 你看下我改的对不?
11-20
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值