zoukankan      html  css  js  c++  java
  • Golang时间字符串转换计算器

    [本文出自天外归云的博客园]

    分享一个常用的时间字符串的加减的小方法,可以把一种格式的时间字符串转化成日期时间后加减天数,再转化为目标格式返回。

    代码:

    package pintia
    
    import (
    	"fmt"
    	"time"
    )
    
    // TimeStrConverter 时间字符串转换计算器
    type TimeStrConverter struct {
    	InputDateFormat  string
    	OutPutDateFormat string
    }
    
    // AddDuration 时间字符串加减天
    // dateStr 是输入的时间字符串
    // n 天数(负数为减,正数为加)
    func (t *TimeStrConverter) AddDuration(dateStr string, n int) (string, error) {
    	// 1. 将dateStr按指定格式转换成时间
    	endDate, err := time.Parse(t.InputDateFormat, dateStr)
    	if err != nil {
    		return "", err
    	}
    	// 2. 加上n天——24*n小时
    	durationStr := fmt.Sprintf("%+vh", 24*n)
    	duration, _ := time.ParseDuration(durationStr)
    	startDate := endDate.Add(duration)
    	// 3. 将计算后的日期转成指定格式的时间字符串
    	startDateStr := startDate.Format(t.OutPutDateFormat)
    	return startDateStr, nil
    }
    

    测试代码:

    package pintia
    
    import (
    	"testing"
    
    	"github.com/stretchr/testify/assert"
    )
    
    func TestDateStrAddDuration(t *testing.T) {
    	// 准备测试数据
    	inputDateStr := "20210630"
    	durationDays := -3
    	timeStrConverter := TimeStrConverter{InputDateFormat: "20060102", OutPutDateFormat: "2006-01-02"}
    	// 执行待测方法
    	outputDateStr, err := timeStrConverter.AddDuration(inputDateStr, durationDays)
    	t.Logf("outputDateStr->%+v", outputDateStr)
    	// 断言
    	assert.Nil(t, err)
    	assert.Equal(t, "2021-06-27", outputDateStr)
    }
    

    运行结果:

  • 相关阅读:
    (18)随机数
    JMeter 正则表达式提取器(二)
    swiper控件(回调函数)
    移动测试之appium+python 导出报告(六)
    移动测试之appium+python 简单例子(五)
    移动测试之appium+python 入门代码(四)
    移动测试之appium+python 入门代码(三)
    移动测试之appium+python 入门代码(二)
    移动测试之appium+python 环境安装(一)
    网站架构模式(二)
  • 原文地址:https://www.cnblogs.com/LanTianYou/p/14956349.html
Copyright © 2011-2022 走看看