search
HomeWeb Front-endHTML TutorialImplement date picker effect in WeChat applet

Implement date picker effect in WeChat applet

Nov 21, 2023 am 10:31 AM
WeChat appletaccomplishdate picker

Implement date picker effect in WeChat applet

With the widespread application of WeChat mini programs, more and more developers need to implement date picker effects to improve user experience. This article will introduce how to implement the date picker effect in WeChat applet and give specific code examples.

1. Implementation ideas

The basic idea to achieve the date picker effect is: first create a date picker component in WXML, dynamically generate date data through JavaScript, and then listen to the change of the component event to obtain the date information selected by the user.

2. Implementation process

  1. Create a date picker component in WXML

We can use the picker-view component provided by the WeChat applet to implement Date picker effect. The picker-view component can render list-like content into a scrolling picker.

In WXML, we can write like this:

<picker-view bindchange="onDateChange" value="{{dateIndex}}" style="width: 100%; height: 200rpx;">
  <picker-view-column>
    <view wx:for="{{years}}" wx:key="year">{{item}}年</view>
  </picker-view-column>
  <picker-view-column>
    <view wx:for="{{months}}" wx:key="month">{{item}}月</view>
  </picker-view-column>
  <picker-view-column>
    <view wx:for="{{days}}" wx:key="day">{{item}}日</view>
  </picker-view-column>
</picker-view>

The above code creates a picker-view component and binds the onDateChange event and dateIndex variable. Among them, the years, months and days variables are used to store the generated year, month and day data.

  1. JavaScript dynamically generates date data

In order to generate date data, we need to obtain the current year, month and day, and then use a relatively simple algorithm to generate the year, month and day respectively. Array of month and day.

In JavaScript, we can write like this:

Page({
  data: {
    years: [],
    months: [],
    days: [],
    dateIndex: 0
  },
  onLoad: function () {
    // 获取当前年月日
    var datetime = new Date();
    var year = datetime.getFullYear();
    var month = datetime.getMonth() + 1;
    var day = datetime.getDate();

    // 设置年份数组,从当前年往前推 100 年
    var years = [];
    for (var i = year; i >= year - 100; i--) {
      years.push(i);
    }

    // 设置月份数组
    var months = [];
    for (var i = 1; i <= 12; i++) {
      months.push(i);
    }

    // 设置日期数组,根据年月计算出当月的天数
    var days = [];
    var dayCount = this.getDaysOfMonth(year, month);
    for (var i = 1; i <= dayCount; i++) {
      days.push(i);
    }

    // 更新数据
    this.setData({
      years: years,
      months: months,
      days: days
    });
  },
  // 根据年月获取当月的天数
  getDaysOfMonth: function (year, month) {
    var dayCount = 31;
    switch (month) {
      case 2:
        if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
          dayCount = 29;
        } else {
          dayCount = 28;
        }
        break;
      case 4:
      case 6:
      case 9:
      case 11:
        dayCount = 30;
        break;
    }
    return dayCount;
  },
  // 监听日期选择器的 change 事件,更新 dateIndex 变量
  onDateChange: function (e) {
    this.setData({
      dateIndex: e.detail.value
    });
  }
});

The above code first gets the current year, month and day, then calculates the number of days in the current month based on the year and month, and adds the year, month and The days are stored in the years, months and days arrays respectively.

In the onLoad function, we call the getDaysOfMonth function to get the number of days in the current month, and save the obtained year, month, and day data into the data variable. We can also set the initial dateIndex variable to 0 in the onLoad function.

In the onDateChange function, we use the setData function to update the dateIndex variable and record the date information selected by the user.

3. Code example

The complete WeChat applet code is as follows:

<page>
  <view class="page__body">
    <picker-view bindchange="onDateChange" value="{{dateIndex}}" style="width: 100%; height: 200rpx;">
      <picker-view-column>
        <view wx:for="{{years}}" wx:key="year">{{item}}年</view>
      </picker-view-column>
      <picker-view-column>
        <view wx:for="{{months}}" wx:key="month">{{item}}月</view>
      </picker-view-column>
      <picker-view-column>
        <view wx:for="{{days}}" wx:key="day">{{item}}日</view>
      </picker-view-column>
    </picker-view>
  </view>
</page>
Page({
  data: {
    years: [],
    months: [],
    days: [],
    dateIndex: 0
  },
  onLoad: function () {
    // 获取当前年月日
    var datetime = new Date();
    var year = datetime.getFullYear();
    var month = datetime.getMonth() + 1;
    var day = datetime.getDate();

    // 设置年份数组,从当前年往前推 100 年
    var years = [];
    for (var i = year; i >= year - 100; i--) {
      years.push(i);
    }

    // 设置月份数组
    var months = [];
    for (var i = 1; i <= 12; i++) {
      months.push(i);
    }

    // 设置日期数组,根据年月计算出当月的天数
    var days = [];
    var dayCount = this.getDaysOfMonth(year, month);
    for (var i = 1; i <= dayCount; i++) {
      days.push(i);
    }

    // 更新数据
    this.setData({
      years: years,
      months: months,
      days: days
    });
  },
  // 根据年月获取当月的天数
  getDaysOfMonth: function (year, month) {
    var dayCount = 31;
    switch (month) {
      case 2:
        if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
          dayCount = 29;
        } else {
          dayCount = 28;
        }
        break;
      case 4:
      case 6:
      case 9:
      case 11:
        dayCount = 30;
        break;
    }
    return dayCount;
  },
  // 监听日期选择器的 change 事件,更新 dateIndex 变量
  onDateChange: function (e) {
    this.setData({
      dateIndex: e.detail.value
    });
  }
});

4. Summary

This article introduces how to use WeChat applet Implement the date picker effect, including creating a date picker component, dynamically generating date data, and listening to the component's change event to obtain the date information selected by the user. Through the examples in this article, readers can understand the basic development process of WeChat applet and master the method of using the picker-view component. Readers can implement their own date picker effects based on the sample code in this article.

The above is the detailed content of Implement date picker effect in WeChat applet. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What is the difference between an HTML tag and an HTML attribute?What is the difference between an HTML tag and an HTML attribute?May 14, 2025 am 12:01 AM

HTMLtagsdefinethestructureofawebpage,whileattributesaddfunctionalityanddetails.1)Tagslike,,andoutlinethecontent'splacement.2)Attributessuchassrc,class,andstyleenhancetagsbyspecifyingimagesources,styling,andmore,improvingfunctionalityandappearance.

The Future of HTML: Evolution and TrendsThe Future of HTML: Evolution and TrendsMay 13, 2025 am 12:01 AM

The future of HTML will develop in a more semantic, functional and modular direction. 1) Semanticization will make the tag describe the content more clearly, improving SEO and barrier-free access. 2) Functionalization will introduce new elements and attributes to meet user needs. 3) Modularity will support component development and improve code reusability.

Why are HTML attributes important for web development?Why are HTML attributes important for web development?May 12, 2025 am 12:01 AM

HTMLattributesarecrucialinwebdevelopmentforcontrollingbehavior,appearance,andfunctionality.Theyenhanceinteractivity,accessibility,andSEO.Forexample,thesrcattributeintagsimpactsSEO,whileonclickintagsaddsinteractivity.Touseattributeseffectively:1)Usese

What is the purpose of the alt attribute? Why is it important?What is the purpose of the alt attribute? Why is it important?May 11, 2025 am 12:01 AM

The alt attribute is an important part of the tag in HTML and is used to provide alternative text for images. 1. When the image cannot be loaded, the text in the alt attribute will be displayed to improve the user experience. 2. Screen readers use the alt attribute to help visually impaired users understand the content of the picture. 3. Search engines index text in the alt attribute to improve the SEO ranking of web pages.

HTML, CSS, and JavaScript: Examples and Practical ApplicationsHTML, CSS, and JavaScript: Examples and Practical ApplicationsMay 09, 2025 am 12:01 AM

The roles of HTML, CSS and JavaScript in web development are: 1. HTML is used to build web page structure; 2. CSS is used to beautify the appearance of web pages; 3. JavaScript is used to achieve dynamic interaction. Through tags, styles and scripts, these three together build the core functions of modern web pages.

How do you set the lang attribute on the  tag? Why is this important?How do you set the lang attribute on the tag? Why is this important?May 08, 2025 am 12:03 AM

Setting the lang attributes of a tag is a key step in optimizing web accessibility and SEO. 1) Set the lang attribute in the tag, such as. 2) In multilingual content, set lang attributes for different language parts, such as. 3) Use language codes that comply with ISO639-1 standards, such as "en", "fr", "zh", etc. Correctly setting the lang attribute can improve the accessibility of web pages and search engine rankings.

What is the purpose of HTML attributes?What is the purpose of HTML attributes?May 07, 2025 am 12:01 AM

HTMLattributesareessentialforenhancingwebelements'functionalityandappearance.Theyaddinformationtodefinebehavior,appearance,andinteraction,makingwebsitesinteractive,responsive,andvisuallyappealing.Attributeslikesrc,href,class,type,anddisabledtransform

How do you create a list in HTML?How do you create a list in HTML?May 06, 2025 am 12:01 AM

TocreatealistinHTML,useforunorderedlistsandfororderedlists:1)Forunorderedlists,wrapitemsinanduseforeachitem,renderingasabulletedlist.2)Fororderedlists,useandfornumberedlists,customizablewiththetypeattributefordifferentnumberingstyles.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use