时间选择器仍然无法在选择时间后在时间选择器中显示正确格式类型的时间:yyyy-mm-dd
时间: 2025-02-23 21:32:42 浏览: 56
在您的代码中,时间选择器在选择时间后未能正确显示格式化的时间。这可能是由于时间格式化方法没有正确调用或应用。以下是解决方案:
### 解决方案
1. **确保 `formatTimestamp` 方法被正确调用**:
在 `confirm` 方法中,您已经调用了 `formatTimestamp` 方法来格式化时间。但为了确保时间选择器中的显示也是正确的,可以在 `u-cell` 组件中直接使用格式化后的值。
2. **更新 `u-cell` 组件中的显示值**:
将 `u-cell` 组件中的 `:value` 绑定改为格式化后的值。
### 修改后的代码
```vue
<template>
<div class="container">
<div v-if="dataLoaded" class="form-container">
<!-- 表单部分 -->
<u-form @submit.prevent="updateData">
<div class="form-group">
<label for="DANGER_PIC">隐患图片:</label>
<img :src="editableData.DANGER_PIC" height="150" width="150" alt="隐患图片" class="danger-pic" />
</div>
<div class="form-group">
<label for="DANGER_GRADE">隐患等级:</label>
<input id="DANGER_GRADE" v-model="editableData.DANGER_GRADE" type="text" disabled />
</div>
<div class="form-group">
<label for="DANGER_DESC">隐患描述:</label>
<input id="DANGER_DESC" v-model="editableData.DANGER_DESC" type="text" disabled />
</div>
<div class="form-group">
<label for="CORRE_FINTIME">整改完成时间:</label>
<u-cell-group>
<u-cell
@click="showDatetimePicker"
title="年月日"
isLink
:value="formattedCORRE_FINTIME"
>
</u-cell>
<u-datetime-picker
:show="show2"
v-model="editableData.CORRE_FINTIME"
mode="date"
closeOnClickOverlay
@confirm="confirm"
@cancel="cancel"
@change="change"
@close="close"
></u-datetime-picker>
</u-cell-group>
</div>
<u-form-item class="upload" label="整改图片" prop="upload">
<u-upload :fileList="fileList" :previewFullImage="true" @afterRead="afterRead" @delete="deletePic"
:maxCount="1" width="80" height="80"></u-upload>
<u-button type="primary" @click="takePhoto">拍照上传</u-button>
</u-form-item>
<!-- 提交按钮(如果需要修改数据,可以启用并提交) -->
<button type="submit" @click.prevent="handleSubmit" class="submit-button">保存</button>
</u-form>
</div>
</div>
</template>
<script>
import request from '@/utils/request';
import { getToken } from '@/utils/auth';
export default {
data() {
const d = new Date();
return {
data: null,
editableData: {
CORRE_FINTIME: Number(d) // 初始化时间选择器的值
},
fileList: [],
dataLoaded: false,
selectedRecordId: null, // 用于存储从上一个页面传递的记录ID
show2: false,
};
},
methods: {
formatTimestamp(timestamp) {
const date = new Date(timestamp);
return date.toISOString().substring(0, 10); // 格式化为 YYYY-MM-DD
},
takePhoto() {
uni.chooseImage({
count: 1, // 默认9
sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['camera'], // 只能选择拍照
success: (res) => {
const tempFilePaths = res.tempFilePaths;
this.fileList = [ // 更新 fileList
{
url: tempFilePaths[0],
status: 'success',
message: ''
}
];
// 保存图片到相册
uni.saveImageToPhotosAlbum({
filePath: tempFilePaths[0],
success: function() {
uni.showToast({
title: '已保存到相册',
icon: 'success'
});
},
fail: function(err) {
uni.showToast({
title: '保存失败,请检查权限设置',
icon: 'none'
});
console.error('保存图片到相册失败:', err);
}
});
console.log(this.fileList);
}
});
},
async afterRead(event) {
let lists = [].concat(event.file);
let fileListLen = this[`fileList${event.name}`].length;
lists.map((item) => {
this[`fileList${event.name}`].push({
...item,
status: 'uploading',
message: '上传中'
});
});
for (let i = 0; i < lists.length; i++) {
const result = await this.uploadFilePromise(lists[i].url);
let parsedResult = JSON.parse(result);
let item = this[`fileList${event.name}`][fileListLen];
this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
status: 'success',
message: '',
url: parsedResult.data
}));
fileListLen++;
}
console.log(this.fileList);
},
deletePic(e) {
this['fileList'].splice(0, 1);
},
uploadFilePromise(url) {
const header = {
'Authorization': `Bearer ${getToken()}`
};
return new Promise((resolve, reject) => {
uni.uploadFile({
url: 'http://27.156.229.2:9001/api/danger_rectify_record/upload',
filePath: url,
header: header,
name: 'fileinput',
success: (res) => {
console.log('Upload success:', res);
resolve(res.data);
},
fail: (err) => {
console.error('Upload failed:', err);
reject(err);
}
});
});
},
fetchData() {
const params = {
page: 1,
rows: 30,
sort: "DANGER_R_ID",
order: "desc",
wheres: JSON.stringify([{
name: "ORDER_STATUS",
value: "1"
},
{
name: "DANGER_R_ID",
value: this.selectedRecordId
}])
};
request({
url: '/api/danger_rectify_record/getPageData',
method: 'POST',
header: {
'content-type': 'application/json',
'Authorization': `Bearer ${getToken()}`
},
data: params,
dataType: 'json'
}).then(response => {
this.data = response;
if (this.data.rows.length > 0) {
this.editableData = {
...this.data.rows[0]
};
}
this.editableData.DANGER_PIC = 'http://27.156.229.2:9001/' + this.editableData.DANGER_PIC
console.log(this.editableData.DANGER_PIC)
this.dataLoaded = true;
}).catch(error => {
console.error(error);
uni.showToast({
title: '请求失败',
icon: 'none'
});
});
},
handleSubmit() {
console.log(this.editableData);
const mainData = {};
if (this.fileList.length !== 0) {
mainData.CORRE_FINPIC = this.fileList[0].url + this.fileList[0].name; // 使用 fileList 中的路径
}
if (this.editableData.CORRE_FINTIME) {
mainData.CORRE_FINTIME = this.editableData.CORRE_FINTIME; // 直接发送 YYYY-MM-DD 格式的日期
}
mainData.DANGER_R_ID = this.editableData.DANGER_R_ID;
mainData.ORDER_STATUS = 2;
console.log(mainData);
request({
url: '/api/Rectification/update',
method: 'POST',
header: {
'content-type': 'application/json',
'Authorization': `Bearer ${getToken()}`
},
data: {
mainData
},
dataType: 'json'
}).then(response => {
console.log(response);
uni.showToast({
title: '更新成功',
icon: 'success'
});
}).catch(error => {
console.error(error);
uni.showToast({
title: '更新失败',
icon: 'none'
});
});
},
close() {
this.show2 = false;
},
cancel() {
this.show2 = false;
},
confirm(e) {
this.show2 = false;
this.editableData.CORRE_FINTIME = this.formatTimestamp(e.value);
},
change(e) {
// console.log('change', e);
},
result(time, mode) {
const timeFormat = uni.$u.timeFormat,
toast = uni.$u.toast;
if (mode === 'date') {
return toast(timeFormat(time, 'yyyy-mm-dd'));
}
return '';
},
showDatetimePicker() {
this.show2 = true;
},
},
computed: {
formattedData() {
return this.data ? JSON.stringify(this.data, null, 2) : '';
},
formattedCORRE_FINTIME() {
return this.editableData.CORRE_FINTIME ? this.formatTimestamp(this.editableData.CORRE_FINTIME) : '';
}
},
onLoad(options) {
this.selectedRecordId = options.recordId;
this.fetchData();
},
mounted() {
this.fetchData();
if (this.editableData.CORRE_FINTIME) {
this.editableData.CORRE_FINTIME = this.formatTimestamp(this.editableData.CORRE_FINTIME);
}
},
};
</script>
<style lang="scss">
.container {
padding: 20px;
max-width: 600px;
margin: 0 auto;
}
.form-container {
background-color: #f9f9f9;
border: 1px solid #ddd;
border-radius: 8px;
padding: 20px;
}
.form-group {
display: flex;
align-items: center;
margin-bottom: 15px;
label {
width: 120px;
font-weight: bold;
margin-right: 10px;
}
input[type="text"] {
flex: 1;
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
}
span {
flex: 1;
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
}
.u-datetime-picker {
flex: 1;
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
}
}
.submit-button {
background-color: #007bff;
color: white;
border: none;
padding: 10px 20px;
border-radius: 4px;
cursor: pointer;
transition: background-color 0.3s ease;
&:hover {
background-color: #0056b3;
}
}
</style>
```
### 关键点
- **计算属性 `formattedCORRE_FINTIME`**:用于格式化 `editableData.CORRE_FINTIME` 并在 `u-cell` 组件中显示。
- **`u-cell` 组件中的 `:value` 绑定**:绑定到 `formattedCORRE_FINTIME`,确保显示的是格式化后的日期。
这样修改后,时间选择器在选择时间后会正确显示格式化的时间 `yyyy-mm-dd`。
阅读全文
相关推荐

















