菜鸟教程小白 发表于 2022-12-13 05:40:48

ios - 我应该怎么做才能根据所选的语言环境正确显示日期?


                                            <p><p>我使用日期格式“MM/dd/yyyy h:mm a”。但是当我使用不同的语言环境时,日期几乎没有变化。</p>

<pre><code>let date = Date()
let formatter = DateFormatter()
formatter.dateFormat = &#34;MM/dd/yyyy h:mm a&#34;

formatter.locale = Locale(identifier: &#34;de_DE&#34;)
result = formatter.string(from: date) // 09/10/2019 2:41 PM

formatter.locale = Locale(identifier: &#34;es_ES&#34;)
result = formatter.string(from: date) // 09/10/2019 2:41 p. m.

</code></pre>

<p>但是当我使用这个 dateFormat "MM/dd/yyyy j:mm a"并以这种方式使用它时
<code>formatter.dateFormat = DateFormatter.dateFormat(fromTemplate: "MM/dd/yyyy j:mm a", options: 0, locale: Locale(identifier: "de_DE"))</code>
我有重大变化。</p>

<pre><code>formatter.dateFormat = &#34;MM/dd/yyyy j:mm a&#34;
formatter.dateFormat = DateFormatter.dateFormat(fromTemplate: &#34;MM/dd/yyyy j:mm a&#34;, options: 0, locale: Locale(identifier: &#34;de_DE&#34;))
      result = formatter.string(from: date) // 10.09.2019, 14:41
formatter.dateFormat = DateFormatter.dateFormat(fromTemplate: &#34;MM/dd/yyyy j:mm a&#34;, options: 0, locale: Locale(identifier: &#34;es_ES&#34;))
      result = formatter.string(from: date) // 10/09/2019 14:41
</code></pre>

<p>如何不使用日期格式的“j”?我应该怎么做才能根据所选的语言环境正确显示日期?</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>来自文档:<a href="https://developer.apple.com/documentation/foundation/dateformatter/1413514-dateformat" rel="noreferrer noopener nofollow">link</a> </p>

<p>你需要使用,</p>

<pre><code>formatter.dateFormat = &#34;MM/dd/yyyy h:mm a&#34;
</code></pre>

<p>仅适用于固定格式的字符串。因此,如果您使用它,语言环境将不会有任何影响。要使语言环境生效,您需要使用,</p>

<pre><code>formatter.dateStyle = .short
formatter.timeStyle = .short
</code></pre>

<p>方法或者你提到的,</p>

<pre><code>class func dateFormat(fromTemplate tmplate: String,
            options opts: Int,
               locale: Locale?) -&gt; String?
</code></pre>

<p>方法。就 j 而言,我没有看到任何目的。您可以使用上面的“dateFormatfromTemplate”方法与相同的格式字符串。</p></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 我应该怎么做才能根据所选的语言环境正确显示日期?,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/57870252/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/57870252/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 我应该怎么做才能根据所选的语言环境正确显示日期?