Appery.io无映射场景下NOAA API潮汐时间格式改写问题
解决方案
针对你遇到的NOAA潮汐数据时间格式化问题,根据不同使用场景,有以下几种直接可行的放置方式:
1. 数据获取后预处理(推荐)
在拿到API返回数据后,立刻遍历predictions数组,用你的TS格式化函数替换每个项的t字段,之后再将处理好的数据绑定到网格。这种方式只处理一次数据,性能更优,且所有使用该数据的地方都能直接用格式化后的结果。
示例代码:
// 中文时间格式化函数(可按需调整) function formatTideTime(utcStr: string): string { const date = new Date(utcStr + 'Z'); // 补充Z标识UTC时间 const monthNames = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']; const month = monthNames[date.getUTCMonth()]; const day = date.getUTCDate(); let hours = date.getUTCHours(); const minutes = date.getUTCMinutes().toString().padStart(2, '0'); const period = hours >= 12 ? '下午' : '凌晨'; // 转换为12小时制 if (hours === 0) { hours = 12; } else if (hours > 12) { hours -= 12; } return `${month}${day}日,${period}${hours}:${minutes}`; } // 获取并预处理潮汐数据 async function fetchAndProcessTideData() { const response = await fetch('你的NOAA API请求地址'); const rawData = await response.json(); // 替换原始时间为格式化后的中文时间 rawData.predictions = rawData.predictions.map(pred => ({ ...pred, t: formatTideTime(pred.t) })); // 将处理后的数据绑定到网格 // 例如:gridDataSource = rawData.predictions; return rawData; }
2. 模板层自定义过滤器/管道(框架场景)
如果你使用Angular、Vue这类支持模板过滤器的框架,可以把格式化逻辑封装成过滤器/管道,直接在模板中调用,无需修改原始数据源。
Angular Pipe示例:
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'formatTideTime' }) export class FormatTideTimePipe implements PipeTransform { transform(utcStr: string): string { // 复用格式化逻辑 const date = new Date(utcStr + 'Z'); const monthNames = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']; const month = monthNames[date.getUTCMonth()]; const day = date.getUTCDate(); let hours = date.getUTCHours(); const minutes = date.getUTCMinutes().toString().padStart(2, '0'); const period = hours >= 12 ? '下午' : '凌晨'; if (hours === 0) { hours = 12; } else if (hours > 12) { hours -= 12; } return `${month}${day}日,${period}${hours}:${minutes}`; } }
模板中使用:
<td>{{ prediction.t | formatTideTime }}</td>
Vue 过滤器示例:
Vue.filter('formatTideTime', function(utcStr) { const date = new Date(utcStr + 'Z'); const monthNames = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']; const month = monthNames[date.getUTCMonth()]; const day = date.getUTCDate(); let hours = date.getUTCHours(); const minutes = date.getUTCMinutes().toString().padStart(2, '0'); const period = hours >= 12 ? '下午' : '凌晨'; if (hours === 0) { hours = 12; } else if (hours > 12) { hours -= 12; } return `${month}${day}日,${period}${hours}:${minutes}`; });
模板中使用:
<td>{{ prediction.t | formatTideTime }}</td>
3. 原生模板字符串渲染(无框架场景)
如果是用原生JS/TS拼接HTML渲染网格,在生成每行内容时直接调用格式化函数:
function renderTideGrid(predictions) { const gridBody = document.getElementById('tide-grid-body'); if (!gridBody) return; gridBody.innerHTML = predictions.map(pred => ` <tr> <td>${formatTideTime(pred.t)}</td> <!-- 其他字段渲染 --> </tr> `).join(''); }
内容的提问来源于stack exchange,提问作者Kevin Keras
相关产品推荐
相关产品推荐

