Created
March 31, 2015 08:45
-
-
Save naoyeye/4c45fecb4756ad8b5fbb to your computer and use it in GitHub Desktop.
时间转换
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function moment(timestamp) { | |
| var dateTarget = new Date(timestamp.replace(/-/g, '/')); // fix for iOS e.g: http://stackoverflow.com/questions/5324178/javascript-date-parsing-on-iphone | |
| var dateCurrent = new Date(); | |
| var textMinute = dateTarget.getMinutes(); | |
| var textHour = dateTarget.getHours(); | |
| if (textMinute < 10) { | |
| textMinute = '0' + dateTarget.getMinutes(); | |
| } | |
| if (textHour < 10) { | |
| textHour = '0' + dateTarget.getHours(); | |
| } | |
| var textTime = textHour + ':' + textMinute; | |
| var textDate = (dateTarget.getMonth() + 1) + '月' + dateTarget.getDate() + '日'; | |
| var textYear = dateTarget.getFullYear() + '年'; | |
| var seconds = Math.floor((dateCurrent - dateTarget) / 1000); | |
| if (seconds === 0 || seconds < 0) { | |
| return '刚刚'; | |
| } | |
| if (seconds < 5) { | |
| return ' ' + seconds + ' 秒前'; | |
| } | |
| if (seconds < 10) { | |
| return ' 5 秒前'; | |
| } | |
| if (seconds < 60) { | |
| return ' ' + Math.floor(seconds / 10) * 10 + ' 秒前'; | |
| } | |
| if (seconds < 3600) { | |
| return ' ' + Math.floor(seconds / 60) + ' 分钟前'; | |
| } | |
| if (seconds < 60 * 70) { | |
| return ' 1 小时前'; | |
| } | |
| if (dateTarget.getFullYear() === dateCurrent.getFullYear()) { | |
| if (dateTarget.getMonth() === dateCurrent.getMonth() && | |
| dateCurrent.getDate() - dateTarget.getDate() < 2) { | |
| if (dateCurrent.getDate() - dateTarget.getDate() === 0) { | |
| return '今天 ' + textTime; | |
| } | |
| return '昨天 ' + textTime; | |
| // @TODO 0331-0401 也要显示昨天 | |
| } | |
| return ' ' + textDate + ' ' + textTime; | |
| } | |
| return ' ' + textYear + textDate + ' ' + textTime; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment